How to pass std :: bind as a universal reference type?

As far as I understand,

  • std::bind perfectly conveys both the called object that it wraps and the arguments of this called object;
  • The returned object std::binditself is movable and / or copyable, depending on whether the called object and its arguments are movable and / or copyable;
  • a The std::bindreturned object may be nested, in which case the external returned object std::bindis movable and / or copyable, just like when binding other called objects.

Therefore, I expect the following code fragment to compile in order. Instead, the code generates a spew of compiler errors in the last two statements in main().

#include <functional>

template<typename HandlerType>
void call_handler(HandlerType&& handler)
{
  handler();
}

template<typename HandlerType>
void do_something(HandlerType&& handler)
{
  auto f = std::bind(
    &call_handler<HandlerType&>,
    std::forward<HandlerType>(handler));
  f();
}

int main()
{
  auto a = [&]() {};
  do_something(a);
  do_something(std::move(a));

  auto b = std::bind([&]() {});
  do_something(b);              // <- compiler error!
  do_something(std::move(b));   // <- compiler error!
}

. , .

g++ 4.9.2 Cygwin f() do_something():

(4 of 103): error: no match for call to ‘(std::_Bind<void (*(std::_Bind<main()::<lambda()>()>))(std::_Bind<main()::<lambda()>()>&)>) ()’

Visual Studio 2013 :

1>C:\Program Files (x86)\Microsoft Visual Studio12.0\VC\include\functional(1149): error C2664: 'void (HandlerType)' : cannot convert argument 1 from 'void' to 'std::_Bind<false,void,main::<lambda_2b8ed726b4f655ffe5747e5b66152230>,> '

? std::bind?

,

  • ?
  • , std::bind , ?
  • , std::bind std::bind?

, .

EDIT: , , , std::ref - , , , f std::bind , a b std::bind call_handler f(), a b f, . , std::bind , , , , , .

+4
1

1 , bind lvalues ​​ , . , bind do_something

auto f = std::bind(
    &call_handler<decltype(handler)>,
    std::forward<HandlerType>(handler));

do_something(std::move(a));

decltype(handler) rvalue, bind call_handler lvalue lambda , main.


, . bind bind, . , . , bind , call_handler, .

Boost boost::protect, bind bind.

, std::protect, .

template<typename T>
struct protect_wrapper : T
{
    protect_wrapper(const T& t) : T(t)
    {}

    protect_wrapper(T&& t) : T(std::move(t))
    {}
};

template<typename T>
std::enable_if_t<!std::is_bind_expression<std::decay_t<T>>::value,
                 T&&
                >
protect(T&& t)
{
    return std::forward<T>(t);
}

template<typename T>
std::enable_if_t<std::is_bind_expression<std::decay_t<T>>::value,
                 protect_wrapper<std::decay_t<T>>
                >
protect(T&& t)
{
    return protect_wrapper<std::decay_t<T>>(std::forward<T>(t));
}

bind protect, .

auto b = protect(std::bind([&]() {}));
do_something(b);
do_something(std::move(b));

+5

All Articles