Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refering to Templates c++

Tags:

c++

templates

Considering Template Class when do we have to refer explicitly to template, and when the compiler "understands that we meant it"

considering the following occurences:

1) function return value & arguements

2) variable declaration inside function

3) namespace SomeClass<T>:: vs. SomeClass::

Is there any rule? I saw sometimes the use is of:

SomeClass

and sometimes: SomeClass<T>

and I didn't get the rule

like image 248
Day_Dreamer Avatar asked Oct 20 '22 17:10

Day_Dreamer


1 Answers

Class template parameters may only be omitted inside the implementation of that class, where they implicitly add the appropriate template specifiers to the class and when referring to a non-dependent base class (non-dependent as in "does not reuse any template arguments"). For example:

template<typename T, typename U>
class C { /* here C is the same as C<T, U> */ };

template<typename T>
class C<void, T> { /* here C is the same as C<void, T> */ };

template<>
class C<void, void> { /* here C is the same as C<void, void> */ };

template<typename> struct Base { };

struct DerivedA : Base<void>
{ /* here Base is the same as Base<void> */ };

template<typename T>
struct DerivedB : Base<T>
{ /* here Base is invalid, since Base<T> depends on a template argument */ };

Function templates may have their template parameters omitted, if they can be deduced from their arguments:

template<typename T>
void f(T f);

f(3); // equivalent to f<int>(3) if no other overload exists

Additionally, there are default template arguments, which leads to something really funky:

template<typename T = void>
class D
{
    // Here D is D<T>, but D<> is D<void> instead!
};
like image 141
gha.st Avatar answered Oct 22 '22 19:10

gha.st