Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ templates without "typename" or "class"

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: Problems writing a copy constructor for a smart pointer

like image 892
Mat Avatar asked Dec 08 '22 01:12

Mat


2 Answers

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

  • The one with class compiles.
  • The one without fails with error: ‘U’ has not been declared.

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.

like image 158
kennytm Avatar answered Dec 30 '22 06:12

kennytm


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.

like image 42
Diego Sevilla Avatar answered Dec 30 '22 06:12

Diego Sevilla