Using template parameters as template parameters
Why is the following cod开发者_StackOverflow中文版e 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.
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
.
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.
精彩评论