gpt4 book ai didi

c++ - 如何存储可变参数模板参数?

转载 作者:IT老高 更新时间:2023-10-28 12:06:15 33 4
gpt4 key购买 nike

是否可以以某种方式存储参数包以供以后使用?

template <typename... T>
class Action {
private:
std::function<void(T...)> f;
T... args; // <--- something like this
public:
Action(std::function<void(T...)> f, T... args) : f(f), args(args) {}
void act(){
f(args); // <--- such that this will be possible
}
}

后来:

void main(){
Action<int,int> add([](int x, int y){std::cout << (x+y);}, 3, 4);

//...

add.act();
}

最佳答案

要在此处完成您想做的事情,您必须将模板参数存储在一个元组中:

std::tuple<Ts...> args;

此外,您必须稍微更改构造函数。特别是,使用 std::make_tuple 初始化 args 并允许在参数列表中使用通用引用:

template <typename F, typename... Args>
Action(F&& func, Args&&... args)
: f(std::forward<F>(func)),
args(std::forward<Args>(args)...)
{}

此外,您必须像这样设置一个序列生成器:

namespace helper
{
template <int... Is>
struct index {};

template <int N, int... Is>
struct gen_seq : gen_seq<N - 1, N - 1, Is...> {};

template <int... Is>
struct gen_seq<0, Is...> : index<Is...> {};
}

您可以使用这样的生成器来实现您的方法:

template <typename... Args, int... Is>
void func(std::tuple<Args...>& tup, helper::index<Is...>)
{
f(std::get<Is>(tup)...);
}

template <typename... Args>
void func(std::tuple<Args...>& tup)
{
func(tup, helper::gen_seq<sizeof...(Args)>{});
}

void act()
{
func(args);
}

那就是它!所以现在你的类应该是这样的:

template <typename... Ts>
class Action
{
private:
std::function<void (Ts...)> f;
std::tuple<Ts...> args;
public:
template <typename F, typename... Args>
Action(F&& func, Args&&... args)
: f(std::forward<F>(func)),
args(std::forward<Args>(args)...)
{}

template <typename... Args, int... Is>
void func(std::tuple<Args...>& tup, helper::index<Is...>)
{
f(std::get<Is>(tup)...);
}

template <typename... Args>
void func(std::tuple<Args...>& tup)
{
func(tup, helper::gen_seq<sizeof...(Args)>{});
}

void act()
{
func(args);
}
};

Here is your full program on Coliru.


更新:这是一个不需要模板参数规范的辅助方法:

template <typename F, typename... Args>
Action<Args...> make_action(F&& f, Args&&... args)
{
return Action<Args...>(std::forward<F>(f), std::forward<Args>(args)...);
}

int main()
{
auto add = make_action([] (int a, int b) { std::cout << a + b; }, 2, 3);

add.act();
}

And again, here is another demo.

关于c++ - 如何存储可变参数模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16868129/

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