It’s hard to get a word for this. Sometimes I see a class like this:
template <typename T>
class Wrapper
{
public:
Wrapper(const T& t) : t_(t) {}
Wrapper(const Wrapper& w) : t_(w.t_) {}
private:
T t_;
}
As far as I can tell this is legitimate code. However, why is the copy constructor allowed to accept a const Wrapper& without explicitly stating that it needs a const Wrapper<T>&. When else is the template type implied? Is it allowed to write the copy constructor this way if you don’t use an in-class definition?
It is explicitly specified by the language standard in 14.6.1/1:
This was re-worded (through the concept of “injected class name”) in the later versions of the standard, but the point is that this behavior is explicitly spelled out in the document.
To answer the second part of your question, this rule also applies to parameter declarations when writing out-of-class method definitions, but it doesn’t apply to the return type declarations. For example, this code is OK
but you can’t remove the
<T>bit from the return type in the definition of the method. (And you can’t remove<T>from the qualified name of the method.)As for the constructior specifically: your should use the full name (with
<T>) for the class, but you should not use<T>in the name of the constructor itself. So the shortest form for out-of-class definition in your case would beNote, that you can’t add the
<T>bit to the constructor name even if you want toP.S. This last claim needs further research. Comeau Online compiler thinks it is an error, while GCC thinks it is OK. I’ll return to it later.
P.P.S. The compiler in MSVC++ 2005 complains about the latter declaration with a warning
Interesting…