qazwsx
qazwsx

Reputation: 26878

How to call a C++ templated function with different data types programmatically?

In my C++ program I need to call a templated function with different data types (int, float, double, char, etc.) and run methods bar1(), bar2().

How to do it without having to explicitly write the call for each type?

foo<int>::bar1()
foo<int>::bar2() 
foo<int>::bar3() 
...


foo<float>::bar1()
foo<float>::bar2() 
foo<float>::bar3() 
...

Upvotes: 2

Views: 619

Answers (5)

H Xu
H Xu

Reputation: 305

I think this is what you are after if you are using C++11. Don't know how to do it with C++03, though.

template<typename Type>
void printAll()
{
    Foo<Type>::bar1();
    Foo<Type>::bar2();
    Foo<Type>::bar3();
}

template <typename Type, typename Type2, typename... RestTypes>
void printAll()
{
    printAll<Type>();
    printAll<Type2, RestTypes...>();
}


int main()
{
    printAll<int, double, float, string>();
    return 0;
}

Upvotes: 1

Paul Manta
Paul Manta

Reputation: 31567

One solution is to use TypeLists. Have a look at boost::mpl::vector, a container of types. Make a recursive function that takes a vector of types as a template parameter (or an iterator of such a vector), then on each following call pass along the iterator to the next type.

Upvotes: 0

Chad
Chad

Reputation: 19032

Since they are void functions in your example, can you rewrite them so that the types can be inferred? Like this:

template <class T>
void example(const T& v)
{
   // do something profound and meaningful here.
   foo<T>::bar1();
   foo<T>::bar2();
   foo<T>::bar3();
}

Now the template type can be inferred by the argument passed to the function:

int x = 0;
double y = 0;
bool b = false;
std::string s = "Hello";

example(x);
example(y);
example(b);
example(s);

Upvotes: 2

Casey Robinson
Casey Robinson

Reputation: 1019

Metaprogramming

Make an array that stores all of the data types you want to test. Then, write a loop to output all of your function calls. Finally, compile and run this generated code.

string types = ["int", "float", "char", "double"];
for(int j=0; j<4; ++j)
 for(int k=0; k<3; ++k)
  cout << "foo<" << types[j] << ">::bar" << k+1 << "();" << endl

Upvotes: 0

Drew Dormann
Drew Dormann

Reputation: 63745

The way you've designed those functions, the types will need to be specified to some degree. They can't be inferred.

You may create a single function so the type only needs to be mentioned once.

template<typename T>
void do_it()
{
  foo<T>::bar1()
  foo<T>::bar2() 
  foo<T>::bar3()
}

Upvotes: 1

Related Questions