C++ 可以接受任何可调用对象的函子类的构造函数

C++ 可以接受任何可调用对象的函子类的构造函数,c++,c++11,c++14,functor,C++,C++11,C++14,Functor,我想创建一个可以接受其他可调用对象的函子类。 例如,我尝试了以下方法: #include <iostream> template<class RetType,class ObjType,class... Params> struct Functor { using FuncSig = RetType (ObjType::*)(Params...); FuncSig funcptr; ObjType *obj; RetType operat

我想创建一个可以接受其他可调用对象的函子类。 例如,我尝试了以下方法:

#include <iostream>
template<class RetType,class ObjType,class... Params>
struct Functor {
    using FuncSig = RetType (ObjType::*)(Params...);
    FuncSig funcptr;
    ObjType *obj;

    RetType operator()(Params... params) {
        return (obj->*funcptr)(params...);
    }
};
class command {
    int x;
    char *ch;
    public:
    void operator()(int a,char *x) {
        // some task
        std::cout << "task1 done!" << std::endl;
    }
};

int main() {
    Functor<void,command,int,char *> f;
    command c;
    f.funcptr = &command::operator();
    f.obj = &c;
    char x[] = {'a','b'};
    f(100,x);
}
#包括
模板
结构函子{
使用FuncSig=RetType(对象类型::*)(参数…);
FuncSig funcptr;
ObjType*obj;
RetType运算符()(参数…参数){
返回(obj->*funcptr)(参数…);
}
};
类命令{
int x;
char*ch;
公众:
void运算符()(int a,char*x){
//一些任务
std::cout使用,您可以执行以下操作:

command c;
std::function<void(int, char *)> f = [&](int n, char* buf){ return c(n, buf); };
char x[] = {'a', 'b'};
f(100, x);

//...
std::function<void(double)> g = normalFunction;
g(1.2);
命令c;
函数f=[&](intn,char*buf){返回c(n,buf);};
字符x[]={'a','b'};
f(100,x);
//...
std::function g=normalFunction;
g(1.2);
使用,您可以执行以下操作:

command c;
std::function<void(int, char *)> f = [&](int n, char* buf){ return c(n, buf); };
char x[] = {'a', 'b'};
f(100, x);

//...
std::function<void(double)> g = normalFunction;
g(1.2);
命令c;
函数f=[&](intn,char*buf){返回c(n,buf);};
字符x[]={'a','b'};
f(100,x);
//...
std::function g=normalFunction;
g(1.2);

Use
std::function
Use
std::function
Hi Jarod42,我有一个问题,我在读“现代C+设计”书。他们深入讨论了函子。可以用std::function代替函子类吗?
std::function
是一个接受函子的函子。当它删除内容时,会有一些额外的成本。它可能有“cleaner”接口,因为它清楚地说明了与常规模板相反的输入/输出。嗨,Jarod42,我有一个问题,我在读“现代C+设计”书。他们深入讨论了函子。std::function可以代替函子类吗?
std::function
是一个接受函子的函子。当它删除其内容时,会有一些额外的成本。它可能有“更干净”的界面,因为它清楚地说明了与常规模板相反的输入/输出。
command c;
std::function<void(int, char *)> f = [&](int n, char* buf){ return c(n, buf); };
char x[] = {'a', 'b'};
f(100, x);

//...
std::function<void(double)> g = normalFunction;
g(1.2);