:: std :: function的constexpr版本 [英] constexpr version of ::std::function
问题描述
我正在寻找可在constexpr中使用的:: std :: function. 用例:我有一个函数,该函数以函数指针作为参数,第二个函数将lambda传递给第一个函数.两者在编译时都是完全可执行的,因此我想对其进行constexpr. 例如:
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);
}
但是,这仅起作用,因为我将lambda转换为函数指针,并且当然无法捕获lambda,如第二个示例所示.谁能给我一些有关捕获lambda的方法的提示?
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?
这将演示用例:
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*/);
}
谢谢, 杰克
推荐答案
我正在寻找可在constexpr中使用的:: std :: function
I am in search of a ::std::function usable in constexpr
在这里停止.不可能. std::function
是一个多态包装函数.无状态Lambda,有状态Lambda,函子,函数指针,函数引用-它们都可以构建有效的std::function
,并且可以在运行时更改.因此,使编译时间等效只是浪费时间.
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;
};
在有问题的代码中,只需接受通用函子,然后使用static_assert
对其进行验证:
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.");
}
这篇关于:: std :: function的constexpr版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!