views:

127

answers:

4

hello!

i'm used to write templates like this:

template<typename T>
void someFunction(SomeClass<T> argument);

however - now I encountered templates in another thread written like this:

template<U>
void someFunction(SomeClass<U> argument);

as far as i know one can use "typename" and "class" interchangably (except for some details regarding nested types..). but what does it mean if i don't put a keyword in the brackets at all?

thanks!

the thread in question: http://stackoverflow.com/questions/561115/problems-writing-a-copy-constructor-for-a-smart-pointer

A: 

I'm sure U is a macro. I don't think a mere typedef would work in place of U, since compilers have to see either of the two keywords 'class' or 'typename' in the brackets in order for templates to compile.

Whoever put 'U' in there was a little too clever for their own good. Thus your confusion.

Welcome to the world of maintaining other peoples dirty code.

C Johnson
How would this theory explain how the second use of U works? :)
UncleBens
A: 

If U is a type than this is a template specialization

harper
I'm sorry, but I don't think so. If you substitute a parameter in the template, it should read `template <>`, and then the actual type used is in the signature of the method/function.
Diego Sevilla
+2  A: 

I think it was just an error of the person asking that forgot to add the "typename" or "class". The answers just copy/pasted the code, and it is also bad.

Diego Sevilla
+10  A: 

That code is wrong (typo). There must be a typename or class in this situation.


However, it does not mean that all template parameters must start with a typename/class. This is because besides types, a template parameter can also be integral constants, so the following code works:

// template <int n>, but n is not used, so we can ignore the name.
template <int>
void foo(std::vector<int>* x) {
}

int main () {
  foo<4>(0);
}

and so is the following:

typedef int U;

// template <U n>, but n is not used, so we can ignore the name.
template <U>
void foo(std::vector<U>* x) {
}

int main () {
  foo<4>(0);
}

This is why I asked if U is a typedef in the comment.

KennyTM
I see - thank you! but what exactly is the point of using template without typename?
Mat
@Mat: If that `n` is really used, we could perform compile-time calculation. On a less-advantage setting, we could use the integer for e.g. an array size `template<class T, int n> struct Foo { T foo[n]; ... };`
KennyTM