如何避免使用std::bind()临时对象进行显式强制转换

How to avoid explicit cast with std::bind() temporary objects?

本文关键字:转换 临时对象 何避免 std bind      更新时间:2023-10-16

std::bind的返回类型(故意)未指定。在std::函数中是可存储的

下面的示例程序展示了如何显式地将std::bind()返回的临时对象强制转换为std::函数,以便调用fn1()。

如果std::bind的返回类型是可知的,则可以重载Callback构造函数&不再需要显式强制转换std::bind临时对象。

是否有办法避免显式强制转换?

// g++ -std=c++11 test.cxx
#include <functional>
using std::placeholders::_1;
class A
{
    public:
        void funcA (int x) { }
};
class Callback
{
    public:
        Callback () = default;
        Callback (std::function<void(int)> f) { }
        // Wish we knew the return type of std::bind()
        // Callback (return_type_of_std_bind f) { }
};
void fn0 (std::function<void(int)> f) { }
void fn1 (Callback cb) { }
int main (void)
{
    A a;
    fn0(std::bind(&A::funcA, &a, _1)); // ok
    fn1(std::function<void(int)>(std::bind(&A::funcA, &a, _1))); // ok, but verbose
    fn1(std::bind(&A::funcA, &a, _1)); // concise, but won't compile
}

可能不相关,但我在Linux上使用gcc 4.7.2

最好给Callback一个通用构造函数:

struct Callback
{
    typedef std::function<void(int)> ftype;
    ftype fn_;
    template <typename T,
              typename = typename std::enable_if<std::is_constructible<ftype, T>::value>::type>
    Callback(T && f) : fn_(std::forward<T>(f))
    { }
};

(我添加了第二个默认模板参数,以便仅对语句有意义的T类型启用此构造函数,以免创建错误的可转换属性。)注意该技术是如何通过为fn_调用一个显式的 con­ struct­来从转换链中移动一个隐式的用户定义转换的。