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

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

user1299 Published in May 28, 2018, 9:48 am

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
        void funcA (int x) { }

class Callback
        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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.363418 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO