gpt4 book ai didi

c++ - 当我在编译时不知道时,如何从 std::tuple 获取第 i 个元素?

转载 作者:IT老高 更新时间:2023-10-28 21:54:13 28 4
gpt4 key购买 nike

我有一个 std::size_t 类型的变量 i 和一个 std::tuple 类型的元组。我想获取元组的 i-th 元素。我试过这个:

// bindings... is of type const T&...
auto bindings_tuple = std::make_tuple(bindings...);
auto binding = std::tuple_element<i, const T&...>(bindings_tuple);

但是我得到这个编译错误,说第一个模板参数必须是一个整数常量表达式:

error: non-type template argument of type 'std::size_t' (aka 'unsigned long') is not an integral constant expression

是否可以获取元组的第 i 元素,以及如何获取?


如果可能的话,我想不使用 boost。

最佳答案

这是可能的:

struct Functor 
{
template<typename T>
void operator()(T& t) const { std::cout << t << std::endl; }
};

template<std::size_t I = 0, typename FuncT, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
for_index(int, std::tuple<Tp...> &, FuncT)
{ }

template<std::size_t I = 0, typename FuncT, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
for_index(int index, std::tuple<Tp...>& t, FuncT f)
{
if (index == 0) f(std::get<I>(t));
for_index<I + 1, FuncT, Tp...>(index-1, t, f);
}

auto t = make_tuple(1, 2, "abc", "def", 4.0f);
int i = 2; // for example
for_index(i, t, Functor());

此代码将打印:

abc

ideone 上的工作示例:sample

关于c++ - 当我在编译时不知道时,如何从 std::tuple 获取第 i 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8194227/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com