gpt4 book ai didi

c++ - 保存并传递给 C++ 中模板参数的函数列表

转载 作者:行者123 更新时间:2023-12-03 07:09:43 25 4
gpt4 key购买 nike

我想保存模板参数列表并将其传递给函数。
点赞std::thread将参数传递给线程。参数类型是模板化的,参数计数不是静态的。
例如,它将如何工作:

class CallbackList {
public:
Callback(/* Type of list of template args */ args) {
this->saved_args = args;
}


void Call() {
this->callback(saved_args);
}
private:
/* Type of list of template args */ saved_args;

CallbackType callback;
}
或者我该如何实现:
template<typename ...Args>
class CallbackList {
public:
using CallbackPrototype = /* some prototype */;

void RegisterCallback(CallbackPrototype callback, Args... args) {
CallbackInfo callback_info;
callback_info.callback = callback;
callback_info.args = { args... };
this->callbacks.push_back(callback_info);
}

void Call() {
for (CallbackInfo& callback_info : this->callbacks)
callback_info.callback(callback_info.args);
}

private:
struct CallbackInfo {
CallbackPrototype callback;
/* what type should be here? tuple? args count are not static */ args;
};

std::vector<CallbackInfo> callbacks;
}
有可能的?
我该如何实现?

最佳答案

如果您不希望回调依赖于参数的类型,则必须使用某种类型的删除。例如,您可以使用 std::function来自 <functional> :

#include <functional>
#include <iostream>


class Lazy_Callback
{
public:
template <typename F, typename ...Args>
Lazy_Callback(F && f, Args && ...args)
: _fun([=]() { return f(args...); })
{ }

void call() const
{
_fun();
}
protected:
private:
std::function<void()> _fun;
};

void print_int(int x)
{
std::cout << "x = " << x << "\n";
}

int main()
{
Lazy_Callback lc(print_int, 5);

lc.call();
}
如果回调可以模板化,那么您可以使用 std::tuple存储您的论点:
#include <tuple>
#include <iostream>



template <typename F, typename ...Args>
class Lazy_Callback
{
public:
template <typename ...Ts>
Lazy_Callback(F f, Ts && ...ts)
: _f(f), _args(ts...)
{ }

void call() const
{
return std::apply(_f, _args);
}

protected:
private:
F _f;
std::tuple<Args...> _args;
};



template <typename F, typename ...Ts>
Lazy_Callback<F, std::decay_t<Ts>...> make_callback(F && f, Ts && ...ts)
{
return { std::forward<F>(f), std::forward<Ts>(ts)... };
}

void print_int(int x)
{
std::cout << "x = " << x << "\n";
}

int main()
{
auto lc = make_callback(print_int, 5);

lc.call();
}

关于c++ - 保存并传递给 C++ 中模板参数的函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64572766/

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