【发布时间】:2018-10-19 12:26:57
【问题描述】:
我的问题是我有一个函数包装器,其中包含一个 std::function 内部。我想要完成的是能够将它分配给 std::function - 就像这样:
std::function a = mywrapper;
它可以工作,但它会丢失有关过程中空的信息 - 即使我的包装类中的 std::function 为空,新创建的函数 a 也不会保留此信息 - 它不能转换为 bool。
如果我的包装器包含一个 nullptr(空)std::function,则函数 a 在赋值后会说它是非空的;即它将布尔转换为真。
有没有办法纠正这种行为?
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::function使用的主体。 -
template
FunctionWrapper ::operator std::function () { return func ; } -
您的运算符重载负责返回未分配的
std::function,而不是包装自身,如果未分配包装的函数。 -
你确定调用了那个方法吗?
-
我们可以得到minimal reproducible example吗?
标签: c++ function stl c++14 std-function