使用模板参数作为模板参数

pyt*_*hor 2 c++ templates template-specialization

为什么以下代码无效?

template <typename S, typename T>
struct B{
    void f(T t, S s) {t.f<S>(s); }
};
Run Code Online (Sandbox Code Playgroud)

gcc 4.3.4抱怨它"期望'>'令牌之前的初级表达",即"S"不是有效的主表达式.

Kon*_*lph 12

您需要指定这f是一个模板:

void f(T t, S s) {
    t.template f<S>(s);
}
Run Code Online (Sandbox Code Playgroud)

C++不知道这一点(此时),因为f类型取决于模板参数的类型T.此外,以下语法将是不明确的:是<指模板列表的开头还是小于运算符?为了帮助C++解决这个问题,你需要指定它f是一个模板,否则C++不能解析下面的部分,因为解析本身取决于它的类型T.