There are a lot of questions at this site with the problems while compiling c++ template code. One of the most common solutions to such problems is to add typename
(and, less frequently, template
) keyword in the right places of the program code:
template<typename T>
class Base
{
public:
typedef char SomeType;
template<typename U>
void SomeMethod(SomeType& v)
{
// ...
}
};
template<typename T>
class Derived : public Base<T>
{
public:
void Method()
{
typename Base<T>::SomeType x;
// ^^^^^^^^
this->template SomeMethod<int>(x);
// ^^^^^^^^
}
};
Whether there is a code that compiles both with and without keyword typename
and gives different results (e.g. output strings)? Similar question for template
keyword.
If not, whether these keywords are really necessary in such meanings?
A small overview of the current situation
@Paul Evans wrote a good answer but it is more suitable for the question "Where and why do I have to put the “template” and “typename” keywords?", not for my question.
@Simple gave an example of the required code for typename
keyword and its possible variation. @Jarod42 gave another variation without any templates, which is probably a gcc bug because it does not compile with clang.
@n.m. gave an example of the required code for template
keyword, @dyp improved it. @n.m. also wrote the another code for both keywords using SFINAE.
@James Kanze in his answer argues that it is impossible to write the required code and any attempts to do it will result in undefined behavior. So the above examples of code are illegal.
It is interesting to find out who is right and what the C++ standard says about this.