Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "a.template foo<0>();" allowed even though "a.foo<0>();" is enough?

struct A
{
    template<int>
    void foo()
    {}
};

int main()
{
    A a;
    a.foo<0>(); // ok
    a.template foo<0>(); // also ok
}

Obviously, a.foo<0>(); is more concise, intuitive, and expressive than a.template foo<0>();.

Why does C++ allow a.template foo<0>(); even though a.foo<0>(); is enough?

like image 825
szxwpmj Avatar asked Mar 18 '18 11:03

szxwpmj


1 Answers

Sometimes, inside a template, you need to write a.template foo<0>() instead of a.foo<0>().

@melpomene gave this great example in the comments:

template<typename T>
void do_stuff() {
  T a;
  a.template foo<0>();
}
do_stuff<A>();

  • In C++03, a.template foo<0>() should not be used in your current situation.

g++ would output the following warning when compiling your code:

warning: 'template' keyword outside of a template [-Wc++11-extensions]

  • In C++11, the grammar has been simplified by allowing the use of the a.template foo<0>() syntax everywhere.
like image 152
Ronan Boiteau Avatar answered Nov 19 '22 15:11

Ronan Boiteau