简体   繁体   中英

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() 
...

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);

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()
}

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;
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM