如何避免显式转换std :: bind()临时对象? [英] How to avoid explicit cast with std::bind() temporary objects?

查看:269
本文介绍了如何避免显式转换std :: bind()临时对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: bind的返回类型(有意)未指定。

The return type of std::bind is (intentionally) unspecified. It is storable in a std::function.

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

The example program below shows how I have to explicitly cast the temporary object returned by std::bind() to a std::function in order to call fn1().

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

If the return type of std::bind was knowable, I could overload the Callback constructor & would no longer need to explicitly cast std::bind temporary objects.

有没有办法避免显式转换?

Is there any way to avoid the explicit cast?

// 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
}

可能不相关, m在

推荐答案

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

Best to give Callback a universal constructor:

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 ,语句是有意义的,因此不会创建虚假的可转换属性。)注意这种技术是如何从转换链中移动一个隐式的用户定义的转换:调用显示 con­ struc­ tor for fn _

(I added the second, defaulted template argument to only enable this constructor for types T for which the statement makes sense, so as not to create false convertibility properties.) Note how this technique re­moves one implicit user-defined conversion from the conversion chain, by invoking an explicit con­struc­tor for fn_.

这篇关于如何避免显式转换std :: bind()临时对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆