Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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

(Note that the std::vector<T> is merely an example). This does not work and gives a compiler error "template declaration of 'void someFunction'". I've already figured out that I need to put a typename in front of type<TT>, i.e.

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

works. But this solution is - to say the least - a bit bulky. Are there alternatives?

like image 235
janitor048 Avatar asked Mar 22 '12 14:03

janitor048


1 Answers

Not only is it bulky but it also prevents template parameter deduction:

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

The alternative (in C++11) is 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 could also use a macro, except that macros are never the right answer.

#define sometype(T) std::vector<T>

template<typename T>
void someFunction( sometype(T) &myArg);

Also, I believe that your definition of sometype isn't valid pre-C++11. It should not have that typename:

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

I think C++11 changes the rule to allow it, but some C++03 compilers failed to correctly diagnose the issue.

like image 143
bames53 Avatar answered Oct 14 '22 07:10

bames53