12
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?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
szxwpmj
  • 465
  • 2
  • 10
  • 12
    Because in some situations `a.template foo<0>` is required, so why not allow it everywhere? – melpomene Mar 18 '18 at 11:10
  • 5
    `template void do_stuff() { T a; a.template foo<0>(); } ... do_stuff();` – melpomene Mar 18 '18 at 11:12
  • 2
    Not allowing it here would require more complexity in the language grammar. – juanchopanza Mar 18 '18 at 11:13
  • 5
    There was a time when it wasn't allowed, matter of fact. C++11 relaxed the requirement to simplify the grammar. Try it with `-std=c++03 -pedantic-errors` and you'll have your compiler complain at you. – StoryTeller - Unslander Monica Mar 18 '18 at 11:26
  • Possible duplicate of [Where and why do I have to put the "template" and "typename" keywords?](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) – ugoren Mar 18 '18 at 19:05

1 Answers1

14

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.
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56