gpt4 book ai didi

c++ - 将函数包装器转换为 std::function

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:51 25 4
gpt4 key购买 nike

我的问题是我有一个函数包装器,其中包含一个 std::function。我想要完成的是能够将它分配给 std::function - 就像那样:

std::function a = mywrapper; 

它有效,但它会丢失有关过程中空的信息 - 即使我的包装类中的 std::function 为空,新创建的函数 a 也不会保留此信息 - 它无法转换为 bool。

如果我的包装器包含一个 nullptr(空)std::function,则函数 a 在赋值后会说它是非空的;即它将 bool 转换为真。

有没有办法纠正这种行为?

FunctionWrapper<void()> wrapper;
std::function<void()> std;
std = wrapper;
std::cout << std::boolalpha << bool(std) << std::endl;

这将解析为 true。它应该解析为 false。

这是 FunctionWrapper 类的标题:

template < class >
class FunctionWrapper;

template<class R, class... ArgTypes>
class FunctionWrapper<R(ArgTypes...)>
{
private:
std::function<R(ArgTypes...)> func = nullptr;

public:
FunctionWrapper() = default;
FunctionWrapper(const FunctionWrapper&) = default;
FunctionWrapper(FunctionWrapper&&) = default;
FunctionWrapper(const boost::function<R(ArgTypes...)>&);
FunctionWrapper(boost::function<R(ArgTypes...)>&&);
template<class F> FunctionWrapper(F);

FunctionWrapper& operator=(const FunctionWrapper&) = default;
FunctionWrapper& operator=(FunctionWrapper&&) = default;
FunctionWrapper& operator=(boost::function<R(ArgTypes...)>&);
FunctionWrapper& operator=(boost::function<R(ArgTypes...)>&&);
template<class F> FunctionWrapper& operator=(F&&);

~FunctionWrapper() = default;

//R operator()(ArgTypes...);

operator std::function<R(ArgTypes...)>();
operator boost::function<R(ArgTypes...)>();
explicit operator bool();

};

最佳答案

我认为这是不可能的,除非语言改变了赋值的工作方式。

当你写 std = wrapper ,这是 std.operator=(wrapper) 的语法糖.我们真的在调用那个函数。这不像初始化,我们还在更顶层考虑转换函数。所以基本上,我们有我们的 function::operator= 选项:

function& operator=( const function& other );                             // #1
function& operator=( function&& other ); // #2
function& operator=( std::nullptr_t ); // #3
template< class F > function& operator=( F&& f ); // #4
template< class F > function& operator=( std::reference_wrapper<F> f ); // #5

#3#5不可行,#4是通过你有一个合适的 operator()#1#2两者都是,出于相同的原因以及您的转换功能的存在。但是#4是完全匹配,而 #1 都不是也不#2是,所以它赢了。句号。

获得#2的唯一方法优于#4 (你真正想要的)是制作#4不是候选人。但是制作#4的唯一方法不是候选人就是要wrapper不可调用。这使得它...根本不是包装器。

所以你在这里基本上不走运。


注意 std::function<void()> std = wrapper;做你想做的事。

关于c++ - 将函数包装器转换为 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52892317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com