C ++ - How to use typedef template workaround in function declaration?

I would like to use a template typedef in various places, among other things, in the declaration of the template function itself. Here is my current attempt

template<typename T> struct type{ typedef std::vector<T> sometype; } template<typename TT> void someFunction( type<TT>::sometype& myArg ); 

(Note that std::vector<T> is just an example). This does not work and gives the compiler error “template declaration“ void someFunction. ”I already realized that I need to put typename in front of type<TT> , i.e.

 template<typename TT> void someFunction( typename type<TT>::sometype& myArg ); 

working. But this decision - at least - is a bit cumbersome. Are there any alternatives?

+7
source share
1 answer

It is not only cumbersome, but also prevents the output of the template:

 std::vector<int> a; someFunction(a); // error, cannot deduce 'TT' someFunction<int>(a); 

An alternative (in C ++ 11) are template aliases:

 template<typename T> using sometype = std::vector<T>; template<typename T> void someFunction(sometype<T> &myArg ); std::vector<int> a; someFunction(a); 

You can also use macros, except that macros are never the correct answer.

 #define sometype(T) std::vector<T> template<typename T> void someFunction( sometype(T) &myArg); 

In addition, I believe your definition of sometype is not valid for pre-C ++ 11. It should not have this name:

 template<typename T> struct type{ typedef std::vector<T> sometype; }; 

I think C ++ 11 modifies the rule to allow it, but some C ++ 03 compilers were unable to correctly diagnose the problem.

+6
source

All Articles