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

有些话、适合烂在心里 提交于 2019-12-08 04:25:58

问题


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

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().

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
}

Probably not relevant, but I'm using gcc 4.7.2 on Linux.


回答1:


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))
    { }
};

(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_.



来源:https://stackoverflow.com/questions/14348681/how-to-avoid-explicit-cast-with-stdbind-temporary-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!