C++ - Why is the 'template' keyword required here?

Consider:

template<typename T>
struct C
{
    struct S
    {
        int a = 99;
    };

    void f(S s, int i)
    {
        s.a<0>(i);
    }
};

template<>
struct C<long>::S
{
    template<int>
    void a(int)
    {}
};

int main()
{
    C<int>{}.f({}, 0); // #1
    C<long>{}.f({}, 0); // #2
}

s.a<0>(i) is parsed as an expression containing of two comparison operations < and >, and this is fine for #1 but fails for #2.

If this is changed to s.template a<0>(i) then #2 is OK and #1 fails. Thus the template keyword is never redundant here.

MSVC is capable of interpreting the expression s.a<0>(i) both ways within the same program. But this is not correct according to the Standard; each expression should have only one parse for the compiler to deal with.


fun may or may not be a template function (or may not exist at all) depending on the template parameter of class C.

That's because you can specialize S (without specializing C):

template <> struct C<int>::S {};

Because the compiler wants to know if fun is a template or not when first looking at class C (prior to substituting the template parameter), template is required.