gpt4 book ai didi

c++ - 是否可以为模板提供可变参数列表或根据提供的参数列表自动生成规范

转载 作者:行者123 更新时间:2023-12-02 01:27:51 25 4
gpt4 key购买 nike

假设我有以下元组:

std::tuple<int, int, int> setVals(int val)
{
return std::make_tuple(val, val, val);
}

使用这样的结构化绑定(bind)真是太好了:auto [x, y, z] = setVals(42);

是否可以为 setVals 提供某种可变参数签名,以便我可以使用任意数量的变量进行结构化绑定(bind)?例如,auto [x, y] = setVals(42);auto [x, y, z, x2, y2, z2] = setVals(42);

我知道我可以使用可变参数函数模板,在其中我可以声明一些整数并将它们作为引用传递,但是结构化绑定(bind)非常方便,我想知道是否可以像我刚刚展示的那样。如果这个问题问得不好,我很抱歉。

最佳答案

您可以创建一个像您想要的那样的函数,但您必须指定元组将具有的元素数量作为模板参数。这会给你这样的代码:

// does the actual creation
template <typename T, std::size_t... Is>
auto create_tuple_helper(const T& initial_value, std::index_sequence<Is...>)
{
// this ueses the comma expression to discard Is and use initial_value instead for each element
return std::tuple{(void(Is), initial_value)...};
// void(Is) is used to get rid of a warning for an unused value
}

// this is a wrapper and makes it easy to call the helper function
template <std::size_t N, typename T>
auto create_tuple(const T& initial_value)
{
return create_tuple_helper(initial_value, std::make_index_sequence<N>{});
}

int main()
{
auto [a, b, c, d] = create_tuple<4>(42);
std::cout << d;
}

Live example

关于c++ - 是否可以为模板提供可变参数列表或根据提供的参数列表自动生成规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74019463/

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