You can also pass pointers to the function and have the function populate the data pointed to by the pointer. This requires creating the vector/list before passing the pointer to it to the function. http://www.cplusplus.com/doc/tutorial/pointers/
1 2 3 4 5 6 7 8
void construct(vector pointer = 0, list pointer = 0, ...){
if(vector pointer != 0){
//do stuff with vector pointer
}
if(list pointer != 0){
//do stuff with list pointer
}
}
There is one other way I can think of, but it is considered to be bad. In this method the function returns a void pointer. The void pointer points to the location of the required type. After calling this function, the pointer needs to be cast back to its original type before it can be used.
1 2 3 4 5 6 7 8 9 10 11 12 13
void*construct(std::string type, ...){
std::vector<int> *vect = new std::vector<int>;
std::list<float> *lis = new std::list<float>;
//do stuff
if(type == "vector"){
delete lis;
return typecasted vect to void*
}
if(type == "list"){
delete vect;
return typecasted lis to void*
}
}
Make sure you clean up after you have finished with the pointer.
template <typename Object>
Object construct(...)
{
....
foo<T>(...) // T refers to the type of the elements of the object, in this case 'int'.
}
Is there any possible way for me to deduce the type of T by just examining the Object?
That is to say, I do NOT want to make construct take two template arguments like this:
construct<vector<int>, int>(...)
/\ To me, that is verbose and redundant. I only want construct to take 'vector<int>' as its template argument, since that does, indeed, contain all the information the function needs in order to run.
#include <iostream>
#include <vector>
template < typename SEQ_CONTAINER > SEQ_CONTAINER construct_from_stdin()
{
SEQ_CONTAINER result ;
typename SEQ_CONTAINER::value_type value ; // the type of values held by the container
while( std::cin >> value ) result.push_back(value) ;
return result ;
}
int main()
{
constauto seq = construct_from_stdin< std::vector<int> >() ;
for( int v : seq ) std::cout << v << ' ' ;
std::cout << '\n' ;
}