Can I use decltype () to avoid code duplication in explicit template instances?

I have a long template function declaration:

template <typename T> void foo(lots ofargs, goin here, andeven more, ofthese arguments, they just, dont stop); 

without overloads. and I want to explicitly create an instance. I can write (say for T = int ):

 template void foo<int>(lots ofargs, goin here, andeven more, ofthese arguments, they just, dont stop); 

But I really don't want to copy this long ad. I would like to say something like:

 template <typename T> using bar = decltype(foo<T>); 

and then:

 template bar<int>; 

Now the first line compiles (GCC 4.9.3), but the second line does not work. Can I make it work? Or can I use decltype() some other way to avoid copying the declaration to instantiate?

Note. I basically used an example in which you cannot infer a type from arguments alone, since I want any solution to support this case as well.

+6
source share
1 answer

Sure. From [temp.explicit]:

The syntax for explicit instantiation is:
explicit specification:
extern opt template Announcement

[...] If an explicit instantiation refers to a function or a member function, the unsigned identifier in the declaration must be either the identifier of the template, or, where all template arguments can be displayed, the name of the template or the identifier of the function operator. [Note: the declaration may declare a qualified identifier, in which case the unqualified-id of the Qualification identifier should be the identifier of the template. -end note]

We need a declaration. Suppose we start with:

 template <class T> void foo(T ) { } 

We can explicitly specialize through simply:

 template void foo<char>(char ); // template-id template void foo(int ); // or just template-name, if the types can be deduced 

This is the same as written:

 using Fc = void(char ); using Fi = void(int ); template Fc foo<char>; template Fi foo; 

What is written:

 template <class T> using F = decltype(foo<T> ); template F<char> foo<char>; template F<int> foo; 

Basically, the reason template bar<int> n’t working is because it is not an ad. You also need a name.

+3
source

All Articles