1

std::bind 的返回类型(有意)未指定。它可以存储在 std::function 中。

下面的示例程序显示了我必须如何将 std::bind() 返回的临时对象显式转换为 std::function 才能调用 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。

4

1 回答 1

11

最好给出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_

于 2013-01-15T23:15:23.823 回答