Bioliquid
Bioliquid

Reputation: 191

Issue with calling static template method inside a template class

I have a template class and a static template method inside. I also have a simple function g, that just allows user to call this method in an appropriate way. This code gives me an error "expected primary-expression before '>' token" inside g function. But if I call a method inside g function like this:

return A<types::a>::f<T>();

In that case code compiles fine and gives no error. How can I possibly fix this issue and what is the problem?

enum class types : uint8_t
{
    a, b
};

template<types type>
struct A {
    template<typename T>
    static T f();
};

template<>
template<typename T>
T A<types::a>::f() {
    cout << "a" << endl;
    return T{};
}

template<>
template<typename T>
T A<types::b>::f() {
    cout << "b" << endl;
    return T{};
}

template<types type, typename T>
T g() {
    return A<type>::f<T>();
}

int main() {
    g<types::a, int>();
}

Upvotes: 2

Views: 42

Answers (1)

Max Langhof
Max Langhof

Reputation: 23711

You need to add a template keyword:

template<types type, typename T>
T g() {
    return A<type>::template f<T>();
}

Demo

A<type>::f is a dependent name (depends on template parameter type). To correctly parse this statement when the template definition is encountered (as required by two-phase-lookup rules), the compiler has to know before instantiation whether f is a variable, a type or a template. It defaults to "it's a variable"; add template to denote a template or typename to denote a type.

Your other case works because in return A<types::a>::f<T>(); there is no dependent name.

Upvotes: 1

Related Questions