1

I get a compilation error (error C2064: term does not evaluate to function taking 0 arguments) when compiling this code in visual studio 2013

#include <string>
#include <iostream>
#include <functional>

template<class F>
void foo(F& callback)
{
    callback();
}

template<class F>
void bar(F& callback)
{
    auto barCallback = std::bind([](F& callback)
    {
        callback();
        std::cout << "world" << std::endl;
    }, std::move(callback));

    foo(barCallback);
}

int main()
{
    std::string s("hello ");
    auto f = std::bind([](std::string& s) { std::cout << s; }, std::move(s));
    bar(f);
}

Basically, what I am trying to achieve here is to move the std::string from main into bar and then into foo (without making copies)

tcb
  • 4,408
  • 5
  • 34
  • 51
  • http://stackoverflow.com/questions/8640393/move-capture-in-lambda – Jay Miller Nov 19 '14 at 18:46
  • That is where I got the idea for using std::move with std::bind :), but now I am stuck with this compilation issue. – tcb Nov 19 '14 at 18:50
  • 1
    You are running into [the special handling of `bind` for bind expressions](http://stackoverflow.com/questions/25841857/vc2013-function-from-bind-not-compiling/25842919#25842919). You need to wipe out the type somehow - e.g., via a `std::function`. – T.C. Nov 19 '14 at 19:30
  • I verified that using `bar(std::function(f))` in `main` solves the issue. Unfortunately, this means the string is copied into the `std::function`, and that is what I wanted to avoid in the first place. – tcb Nov 19 '14 at 19:49
  • And `std::ref` doesn't work? –  Nov 20 '14 at 02:35
  • `std::ref` doesn't work for multi-threaded scenarios. For instance, if `foo` was called on a separate thread. I need the ability to _move_ state into another thread. – tcb Nov 20 '14 at 03:34
  • Then consider writing your own wrapper. – T.C. Nov 21 '14 at 22:04

0 Answers0