constexpr版:: :: std :: function

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

我正在寻找constexpr中可用的:: std :: function。用例:我有一个函数,它将函数指针作为参数,第二个函数将lambda传递给第一个函数。两者在编译时都是完全可执行的,所以我想constexpr它们。例如:

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

但是,这只能起作用,因为我正在将lambda转换为函数指针,当然,如第二个例子中所示,捕获lambdas失败了。谁能给我一些关于如何捕捉lambdas的指示?

这将演示用例:

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*/);
}

谢谢,杰克

c++ metaprogramming c++17 template-meta-programming constexpr
1个回答
4
投票

我正在寻找constexpr中可用的:: std :: function

停在这儿。不可能。 std::function是一个多态包装函数。无状态lambdas,statefull lambdas,仿函数,函数指针,函数引用 - 所有这些都可以构建一个可以在运行时更改的有效std::function。所以使编译时间等效只是浪费时间。

如果您只想要编译时通用函数参数,则可以使用模板

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;

};

在您的代码中,只需接受一个通用仿函数,并使用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.");
}
© www.soinside.com 2019 - 2024. All rights reserved.