call arbitrary functions as First Class Functions in C++

56 Views Asked by At

My intention was to use arbitrary functions as First Class Variables. I used the visitor pattern (at least i think that's what that is) to achieve effectively arbitrary functions as First Class Variables.

Is there a better way to achieve this? Except for safety, is there a big drawback in this design?

Here is a minimal working example, using boost 1.76.0 and C++20 standard:

    boost::variant<void*,int> rep (){
        return 2;
    }
    
    boost::variant<void*,int> oll(){
        std::cout << "happiness" << std::endl;
        return nullptr;
    }
    
    boost::variant<void*,int> iuu(int a ){
        return  a;
    }


    class my_visitor : public boost::static_visitor<boost::variant<void*,int>>
    {
    public:
        boost::variant<void*,int> operator()(boost::variant<void*,int>(*fun)() ) const
        {
            return fun();
        }

        boost::variant<void*,int> operator()(boost::variant<void*,int>(*fun)(int) ) const
        {
    
            return fun(argument);
        }
        int argument;
    };


    int main() {
        boost::variant<boost::variant<void*,int>(*)(), boost::variant<void*,int>(*)(int)> varob(iuu);
        my_visitor vis = my_visitor();
        vis.argument = 22;
        std::cout << boost::apply_visitor(vis, varob);
0

There are 0 best solutions below