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

问题描述 投票:0回答:1

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

#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);
}

这有效。但是,当我想使用普通函数可调用对象时,我需要创建一个不同的Functor类:

#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;
    }
};

template<class RetType,class... Params>
struct Functor2 {
    using FuncSig = RetType (*)(Params...);
    FuncSig funcptr;

    RetType operator()(Params... params) {
        return (*funcptr)(params...);
    }
};
void normalFunction(double x) {
    std::cout << "task2 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);

    //........
    Functor2<void,double> g;
    g.funcptr = normalFunction;
    g(1.2);
}

如何创建通用的Functor类,它可以使用以下可接受的语法接受任何可调用的对象(带有operator()或常规函数的类)。

Functor<ReturnType,int,double,more params ..> F(a_callable_objects);
F(arguments);
c++ c++11 c++14 functor
1个回答
1
投票

使用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);

© www.soinside.com 2019 - 2024. All rights reserved.