7

With

template <typename T>
class Foo {
public:
    template <int x>
    void bar () {}
};

the following compiles:

void fooBar ()
{
    Foo<int> f;
    f.bar<1>();
}

but the following does not (with "error: expected primary-expression before ')' token" in gcc 5.4.0 with -std=c++14).

template <typename T>
void fooBar ()
{
    Foo<T> f;
    f.bar<1>();
}

If I try to explicitly call the second version, with e.g.

fooBar<int>();

then gcc additionally complains about

"invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'".

Is there any reason why the second version is invalid? Why is gcc treating the '<' as an operator rather than the beginning of a template parameter list?

Matt
  • 173
  • 4

1 Answers1

15

With the templated function, the compiler doesn't know exactly what Foo<T> will be (there could be specializations of Foo), so it it has to assume that f.bar is a member variable and parse the code as

f.bar < 1

and then it cannot continue.

You can help the compiler by telling it that bar is a template

f.template bar<1>();
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • This works - and I've never seen this syntax before. I would never have thought of trying this. Thank you! – Matt May 25 '17 at 11:58