Consider the example below:
template <typename T>
class SomeClass {
// rest of the definition ...
SomeClass<T>& function1() {
// ...
return *this;
}
SomeClass& function2() {
// ...
return *this;
}
}
Is there a difference between return values of the two functions above? If not, which one should be preferred?
There is no difference between function1
and function2
. Typing SomeClass
without template arguments in the definition of SomeClass
is an instance of using an injected-class-name:
The injected-class-name is the name of a class within the scope of said class.
In a class template, the injected-class-name can be used either as a template name that refers to the current template, or as a class name that refers to the current instantiation.
It is subjective whether to use one over the other, but the injected class name is more maintainable as it doesn't have to be manually changed if you change the number of template parameters of SomeClass
.