non*_*all 6 c++ parameters templates compilation
好的,我将举一个简单的问题示例:
void Increment(Tuple<int, int>& tuple) {
++tuple.Get<0>();
}
int main() {
Tuple<int, int> tuple;
tuple.Get<0>() = 8;
Increment(tuple);
printf("%i\n", tuple.Get<0>()); // prints 9, as expected
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译得很好,一切都很好.Increment函数只增加元组中的第一个元素,然后我打印该元素.但是,如果我的Increment函数可用于任何类型的元素,那不是很好吗?
template <typename T>
void Increment(Tuple<T, T>& tuple) {
++tuple.Get<0>(); // <-- compile ERROR
}
int main() {
Tuple<int, int> tuple;
tuple.Get<0>() = 8;
Increment<int>(tuple);
printf("%i\n", tuple.Get<0>());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的第二个例子在编译时吐出以下错误:
error: expected primary-expression before ')' token
Run Code Online (Sandbox Code Playgroud)
我最终在试图找出导致问题的原因.由于模板参数为'int',因此生成的代码应与我的硬编码示例相同.我怎样才能让它发挥作用?
GMa*_*ckG 12
它应该是:
++tuple.template Get<0>();
Run Code Online (Sandbox Code Playgroud)
以同样的方式,您需要typename
指定从依赖类型限定的类型,您需要template
指定从依赖类型限定的模板函数.
由于GMan已经给你正确的答案,你仍然可以做的一件事是:你可以简单地写Increment(tuple)
而不是Increment<int>(tuple)
(后一种语法看起来有点复杂).编译器足够智能,可以从类型中推断出函数模板类型tuple
.