Search code examples
c++templatesgeneric-programming

c++ type arguments are omitted in template declaration. However, how about in the definition of member function?


Sorry that I'm a beginner of c++ programming.

As I know, the type arguments in template declaration can be omitted. For example

template<typename T>
class A{
A<T> func(A<T> t);
}

can be written as

template<typename T>
class A{
A func(A t) {}
}

Also, I know that if the member functions are defined outside of the class, the type arguments cannot be omitted. However, I found that the type argument in the function's argument type can be omitted as well. Why is it like this?

I mean for

A<T> A<T>:: func(A<T> t) {}

why the code below is permissible even though it's outside the template declaration?

A<T> A<T>:: func(A t) {}

Solution

  • The reason this works is because A<T>:: scopes the declaration -- everything that follows it knows about the contents of A<T>, including the injected classname A. This is also strictly in source code order, leading to the following curiosity between two semantically identical definitions:

    A A<T>::func(A t) {} // Doesn't work -- `A` is not known before `A<T>::`
    
    auto A<T>::func(A t) -> A {} // Works, because the return type is after `A<T>::`!