Search code examples
c++c++11metaprogrammingtemplate-meta-programmingconstexpr

constexpr version of ::std::function


I am in search of a ::std::function usable in constexpr. Use case: I have a function which takes a function pointer as an argument, and a second which passes a lambda to the first function. Both are fully executable at compile time, so I want to constexpr them. Eg:

template <class _Type>
class ConstexprFunctionPtr
{
    private:
        using Type = typename ::std::decay<_Type>::type;
        const Type function;

    public:
        constexpr inline
        ConstexprFunctionPtr(const Type f)
        : function(f)
        { }

        template <typename... Types>
        constexpr inline
        auto
        operator() (Types... args)
        const {
            return function(args... );
        }
};

constexpr inline
void
test()
{
    ConstexprFunctionPtr<int(int)> test([](int i) -> int {
        return i + 1;
    });
    int i = test(100);

    ConstexprFunctionPtr<int(int)> test2([=](int i) -> int {
        return i + 1;
    });
    i = test2(1000);
}

However, this only works because I am converting the lambda to a function pointer, and of course fails with capturing lambdas as showed in the second example. Can anyone give me some pointers on how to do that with capturing lambdas?

This would demonstrate the usecase:

constexpr
void
walkOverObjects(ObjectList d, ConstexprFunctionPtr<void(Object)> fun) {
// for i in d, execute fun
}

constexpr
void
searchObjectX(ObjectList d) {
walkOverObjects(d, /*lambda that searches X*/);
}

Thanks, jack

Update: Thanks for pointing out the C++20 solution, however, I want one that works under C++14


Solution

  • I am in search of a ::std::function usable in constexpr

    Stop right here. it's impossible. std::function is a polymorphic wrapper function. stateless lambdas, statefull lambdas, functors, function pointers, function references - all of them can build a valid std::function that can change during runtime. so making a compile time equivalent is just a waste of time.

    If you just want a compile time generic function parameter, you can just use templates

    template<class functor_type>
    class my_generic_function_consumer_class{
    
       using decayed_function_type = typename std::decay_t<functor_type>;
    
       decayed_function_type m_functor;
    
    };
    

    In your code in question, just accept a generic functor, and validate it using static_assert:

    template<class function_type>
    constexpr void walkOverObjects(ObjectList d, function_type&& fun) {
        static_assert(std::is_constructible_v<std::function<void(ObjectList), function_type>>,
                      "function_type given to walkOverObjects is invalid.");
    }