使用模板参数作为模板参数 [英] Using template parameters as template parameters
问题描述
为什么下列代码无效?
template <typename S, typename T>
struct B{
void f(T t, S s) {t.f<S>(s); }
};
gcc 4.3.4抱怨期望primary-expression before'>'token'
gcc 4.3.4 complains that it "expected primary-expression before '>' token", i.e. that "S" wasn't a valid primary-expression.
推荐答案
您需要指定 f
是一个模板:
You need to specify that f
is a template:
void f(T t, S s) {
t.template f<S>(s);
}
C ++不知道这一点c> f 的类型取决于模板参数 T
的类型。此外,以下语法将是不明确的:是<
意味着模板列表或小于运算符的开始吗?为了帮助C ++计算出你需要指定 f
是一个模板,否则C ++不能解析下面的部分,因为解析本身取决于类型 T
。
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
.
这篇关于使用模板参数作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!