gpt4 book ai didi

c++ - 通用回调

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:06 27 4
gpt4 key购买 nike

Extends

Related

所以,我正在尝试更好地学习模板元编程,我认为这是一个很好的练习。

我正在尝试编写代码,可以使用我喜欢的传递给它的任意数量的参数来回调函数。

// First function to callint add( int x, int y ) ;// Second function to calldouble square( double x ) ;// Third func to callvoid go() ;

回调创建代码应该如下所示:

// Write a callback object that// will be executed after 42ms for "add"Callback<int, int, int> c1 ;c1.func = add ;c1.args.push_back( 2 );  // these are the 2 argsc1.args.push_back( 5 );  // to pass to the "add" function                         // when it is calledCallback<double, double> c2 ;c2.func = square ;c2.args.push_back( 52.2 ) ;

我在想的是,使用模板元编程我希望能够像这样声明回调,编写这样的结构(请记住这是非常伪代码)

<TEMPLATING ACTION <<ANY NUMBER OF TYPES GO HERE>> >struct Callback{    double execTime ; // when to execute    TYPE1 (*func)( TYPE2 a, TYPE3 b ) ;    void* argList ;   // a stored list of arguments                      // to plug in when it is time to call __func__} ;

所以当用

调用时
Callback<int, int, int> c1 ;

结构会自动为您构造

struct Callback{    double execTime ; // when to execute    int (*func)( int a, int b ) ;    void* argList ;   // this would still be void*,                      // but I somehow need to remember                      // the types of the args..} ;

有没有关于开始编写本文的正确方向的指示?

最佳答案

您可以使用 variadic templates 执行此操作,您的编译器可能不支持。我自己从未使用过它们,因此可能会弄错一些细节,但我会尝试描述它们。

可变参数模板使用“...”运算符。在模板声明(或其他类型表达式)中,省略号表示形式参数可以采用任意数量的参数。

template <typename ... Args>
class Variadic {
public:
operator()(Args&& ... args);
};

在函数调用表达式中,省略号解压其左侧参数。

Variadic<Args>::operator(Args&& ... args) {
func(args...);
}

要转发,您可能需要使用std::forward;这是我的知识变得模糊的一个领域。把这些放在一起,我们得到:

template <typename ReturnValue, typename ... Args>
class Callback {
typedef ReturnValue (*Func)(Args ... args);

double execTime;
Func func;
Args... args;

public:
Callback(double et, Func f) : execTime(et), func(f) {}
ReturnValue operator()(Args&& ... a);
ReturnValue operator()();
};

template <typename ReturnValue, typename ... Args>
ReturnValue Callback<ReturnValue, Args>::operator()(Args&& ... a) {
return (*func)(std::forward(a)...);
}
template <typename ReturnValue, typename ... Args>
ReturnValue Callback<ReturnValue, Args>::operator()() {
return operator(*func)(args...);
}

关于c++ - 通用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2485219/

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