4

When can you omit the C++ template argument list? For example in Visual Studio 2010 this piece of code compiles fine:

template<class T>
Vec2<T> Vec2<T>::operator+ (const Vec2 &v) const
{
    return Vec2(x + v.x, y + v.y);
}

If you inline the code, it actually compiles without any argument list. But is this really the same as the following version?

template<class T>
Vec2<T> Vec2<T>::operator+ (const Vec2<T> &v) const
{
    return Vec2<T>(x + v.x, y + v.y);
}
George
  • 295
  • 4
  • 7

1 Answers1

6

Inside a class you can omit the argument on the class type:

template<typename K>
struct A {
   A<K> foo1; // legal
   A foo2; // also legal and identical to A<K> foo
   A bar(A x) {...} // same as A<K> bar(A<K> x) {...}
};

Outside of a class scope you need the template arguments:

// legal
template<typename K>
A<K> foo(A<K> x) { return A<K>(); }

// illegal!
template<typename K>
A foo(A x) { return A(); }

If you declare a member function outside the class, you need the template list for the return type and for the class:

// legal
template<typename K>
A<K> A<K>::bar(A<K> x) { return A<K>(x); }

// legal
template<typename K>
A<K> A<K>::bar(A x) { return A(x); }

// illegal!
template<typename K>
A A::bar(A<K> x) { return A<K>(x); }
Danvil
  • 22,240
  • 19
  • 65
  • 88
  • 1
    Ok, so I guess, even though the first version compiles without using the argument everywhere, it is probably good style to use it everywhere when declaring/defining a member function outside the class. Thanks! – George Sep 11 '10 at 10:03
  • I missed something out. So the short answer is: Your two versions are identical. – Danvil Sep 11 '10 at 10:19
  • I searched [cppreference.com](http://www.cppreference.com) for an answer before finding this question/answer, but could not find anything. Is it just not mentioned on that site, or did I overlooked it? In particular I am interested in the technical reason. Like: the parameter list is evaluated within the scope of the instantiated class (therefore `A` = `A`), but the return value is not. (Which feels inconsistent, because both make up the signature of the method, do they not?) – Martin Nyolt Jul 19 '15 at 07:22