views:

83

answers:

2

Why is the following code invalid?

template <typename S, typename T>
struct B{
    void f(T t, S s) {t.f<S>(s); }
};

gcc 4.3.4 complains that it "expected primary-expression before '>' token", i.e. that "S" wasn't a valid primary-expression.

+9  A: 

You need to specify that f is a template:

void f(T t, S s) {
    t.template f<S>(s);
}

C++ doesn’t know this (at this point) since f’s type depends on the type of the template parameter T. Furthermore, the following syntax would be ambiguous: does < mean the start of a template list or a less-than operator? To help C++ figure that out you need to specify that f is a template, otherwise C++ cannot parse the following part because the parse itself depends on the type of T.

Konrad Rudolph
+1  A: 

You also can rely on type inference to infer the template type instead of explicitly stating it. Then you would have "t.f(s);", which is actually a slightly more generic way to state it: you probably don't care that f is a templated function, you just want it to have some definition for f that accepts an S.

Chris
pythonic metaphor