将函数包装器转换为 std::function
Converting a function wrapper to std::function
我的问题是我有一个函数包装器,里面包含一个std::function。我想要完成的是能够将其分配给 std::function - 就像这样:
std::function a = mywrapper;
它可以工作,但它在此过程中丢失了有关空的信息 - 即使我的包装类中的 std::function 为空,新创建的函数 a 也不会保留此信息 - 它不能转换为布尔值。
如果我的包装器包含一个 nullptr(空(std::function,函数 a 在赋值后会说它是非空的;即它会布尔转换为 true。
有没有办法纠正这种行为?
FunctionWrapper<void()> wrapper;
std::function<void()> std;
std = wrapper;
std::cout << std::boolalpha << bool(std) << std::endl;
这将解析为 true。它应该解析为假。
下面是 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;
会做你想做的事。
相关文章:
- Confusion: decltype vs std::function
- 为什么 std::function 可以作为 std::not2 的参数?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 传递给std::function template的template参数究竟代表什么
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 将函数包装器转换为 std::function
- 类型擦除的std::function与虚拟函数调用的开销
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 将 lambda 表达式传递给 std::function in C++
- 模板类的部分模板专用化,如 std::function
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 从 std::function in C++ 访问模板化 lambda
- 什么是 std::function::argument_type 的替代品?
- C++派生类重载函数(带有 std::function 参数)不可见
- 如何在 qi 符号表中使用 std::function
- 将 std::function 与模板一起使用
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 我需要在 std::function 上使用 unique_ptr 吗?
- 如何将函数指针从 std::function 传递到 Linux 克隆?