dimanche 22 mars 2020

constructor for functor class that can accept any callable objects

I want to create a functor class that can accept other callable objects. For example I tried the following:

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

This works. But when I want to work with normal function callable object, I need to create a different Functor class:

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

How to create a generic Functor class that can accept any callable objects (class with operator() or normal function) with the following acceptable syntax.

Functor<ReturnType,int,double,more params ..> F(a_callable_objects);
F(arguments);

Aucun commentaire:

Enregistrer un commentaire