【发布时间】:2015-09-17 14:36:54
【问题描述】:
我想编写一个函数来迭代std::tuple<...>。迭代本身不会对元组的模板类型产生任何问题,因为 '...' 具有相同的类型(如 int、int、int、...)。我已经使用模板元编程实现了一个带有辅助结构“Helper”的工作函数“Foo”——一切都很好。
但是,当我想使用 constexpr 函数“helper”来实现替代版本时,编译器 (g++ 5.2.0) 会陷入错误消息的无限循环。根据我从这些消息中可以得到的信息,“位置”模板参数被实例化为大得可笑(== 4294967245)而不是(== 1)。我试图让两个版本在语法和命名上尽可能接近。
小例子
#include <tuple>
// template metaprogramming version
template
<class T, std::size_t position>
struct Helper{
static int
help(T tuple) {
return std::get<position>(tuple) +
Helper<T,position - 1>::help(tuple);
}
};
// template metaprogramming version, specialized
template
<class T>
struct Helper<T,0>{
static int
help(T tuple) {
return std::get<0>(tuple);
}
};
// function version, not working
template
<class T, std::size_t position>
constexpr int
helper(T tuple) {
return
0 == position ?
std::get<position>(tuple) + helper<T,position-1>(tuple) :
std::get<0>(tuple);
}
template
<class T>
auto
Foo(T tuple) {
constexpr std::size_t dimension = std::tuple_size<T>::value;
// working version, using the helper struct
return Helper<T,dimension - 1>::help(tuple);
// wrong(?) version, using the constexpr helper function
return helper<T,dimension - 1>(tuple);
}
int main() {
std::tuple<int,int> t(1,1);
Foo(t);
return 0;
}
我的问题:
- 在编译期间尝试这种迭代主要是错误的吗 使用 constexpr 函数的时间?
- 如果不是,是否是编译器中的错误 或者正确的版本应该是什么样子?
我完全意识到,由于元组中的类型相同(int、int、...),人们可以使用向量实现类似的版本。但我认为元组版本在概念上更适合我的问题,并且在运行时更快。
【问题讨论】:
-
如果你知道元组的所有元素都是同一类型,为什么不使用
std::array?