【发布时间】:2010-12-30 10:34:32
【问题描述】:
好的,我将举一个简单的例子来说明我的问题:
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”,因此生成的代码应该与我的硬编码示例相同。我怎样才能让它工作?
【问题讨论】:
-
GMan 的回答中显示的使用的丑陋和棘手可能是 std 和 boost 元组都有免费的
get函数的原因:++get<0>(tuple);
标签: c++ templates parameters compilation