Home > Net >  Function to explicitly istantiate a given template function with more standard types?
Function to explicitly istantiate a given template function with more standard types?

Time:02-16

I have the following question. Supposing I have a header file header.hpp with this template function declaration:

template <typename T> extern T func();

And in the header.cpp file I have the function definition:

template <typename T> T func() { \* do something */ };

//Following lines are for explicit istantiation of the template for some types:
template double func <double> (); //1
template int func <int>(); //2
//And others...

Does exists a function / class or something else which allows me to explicitly istantiate a template class definition for more templated types without the needing of writing something like lines 1 or 2 of the previous code everytime?

I am searching for something like, for example:

void function ( template_function list_of_types )
 {
  //explicit istantiations of the template_function for the types given in the list_of_types container...
 }

The signature doesn't have to be as the one above, but also similar, the important thing is that it works as I said before. Thanks.

CodePudding user response:

There is no function like that. The explicit template instantiation must appear at namespace scope, so a "function" like that would have to be some sort of compiler magic (that doesn't exist), or use the preprocessor to expand into the required declarations.

Something like Boost.PP has machinery to approximate what you are after. As an example:

#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/to_seq.hpp>

#define ARGS(...) BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__))

template <typename T> void func(T) { };
#define EXPANSION(r, data, elem) template void func<elem>(elem);

BOOST_PP_SEQ_FOR_EACH(EXPANSION, _, ARGS(int,double,char))

See the preprcoessor output live.

It may irritate those with a preprocessor allergy, but it is one of the few legitimate uses for preprocessing remaining. At least until the C standard's committee chooses to give us better tools.

CodePudding user response:

You could use concepts (or requires) and create specialized versions of your template.

So if you have

void func(auto t) { ...}

you could define a concept "AllowedNumericalTypes" and write another template like

void func(AllowedNumericalTypes auto t) { /*1 and 2 */ }

The compiler will choose the most matching version of your func methods and then call those.

btw. template<typename T> void func(T t)
 is identical to 
void func(auto t)
  • Related