为什么我不能将模板参数传递给另一个模板?
好吧,我将给出一个简单的例子来说明我的问题:
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;
}
编译得很好,一切都很顺利。 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;
}
我的第二个示例在编译时出现以下错误:
error: expected primary-expression before ')' token
我束手无策,试图找出为什么这会导致问题。由于模板参数是“int”,生成的代码应该与我的硬编码示例相同。我怎样才能让它发挥作用?
Okay I'm going to give a simple example of my problem:
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;
}
This compiles just fine, and all is peachy. The Increment function just increments the first element in the tuple, and then I print that element. However, wouldn't it be nice if my Increment function could be used on any kind of element?
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;
}
My second example spits out the following error at compile-time:
error: expected primary-expression before ')' token
I'm at my wits end trying to figure out why this causes problems. Since the template parameter is 'int', the generated code should be identical to my hard-coded example. How can I get this to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它应该是:
就像您需要
typename
来指定从依赖类型限定的类型一样,您需要template
来指定从依赖类型限定的模板函数。It should be:
In the same way you need
typename
to specify a type qualified from a dependent type, you needtemplate
to specify a template function qualified from a dependent type.由于 GMan 已经为您提供了正确的 答案,你仍然可以做的一件事是:你可以简单地编写
Increment(tuple)
而不是Increment(tuple)
(后一种语法看起来像有点复杂)。编译器足够智能,可以从元组
的类型推断出函数模板类型。请参阅:http://www.ideone.com/juNOg
Since GMan already gave you the correct answer, one thing you can still do is : you can simply write
Increment(tuple)
instead ofIncrement<int>(tuple)
(the latter syntax looks a bit complex). Compiler is intelligent enough to infer the function-template-type from the type oftuple
.See this : http://www.ideone.com/juNOg