3

More answers: C++ Thread taking reference argument failed compile


I'm creating a callable variable to which I'm assigning a lambda-function with arguments:

auto func = [](int &d) -> void { d++; };

How can I use this variable as a std::thread-function passing my argument?

I tried the obvious:

int i;
auto t1 = std::thread(func, i);
t1.join();

This fails with the compiler telling me that func has no no type named ‘type’ in [..]_Callable(_Args...)>::type result_type;.

EDIT: It is related to the reference of the argument. It works when I pass a pointer (int *i) or a copy (int i).

Community
  • 1
  • 1
Patrick B.
  • 11,773
  • 8
  • 58
  • 101
  • 4
    Try `auto t1 = std::thread(func, std::ref(i));` Unrelated, initialize `i`; ub sucks =P – WhozCraig Feb 20 '17 at 08:45
  • That's it, I just tried and it works. Before you posted your comment ;-) – Patrick B. Feb 20 '17 at 08:47
  • There's a few duplicates to this; I was just too lazy to hunt them down (late here). Sry about that. – WhozCraig Feb 20 '17 at 08:47
  • Maybe there are duplicates, but not with my keywords, neither google nor the the SO-search gave me something useful. – Patrick B. Feb 20 '17 at 08:48
  • @PatrickB. The author of that other question thinks that the problem is in his lambda (which is kind of reasonable because I think that the error message is misleading). To me both questions are exactly the same, but are phrased differently (especially the title) because the author of that other question didn't fully understand what caused the problem. – SingerOfTheFall Feb 20 '17 at 08:55
  • 1
    @SingerOfTheFall After 5+ years of actively using SO I finally understand the usefulness of duplicated questions: it's not the question which is duplicated that makes a question *marked as duplicate* but the answer. My question would produce the same answer! Thanks for enlightening. – Patrick B. Feb 20 '17 at 09:00
  • 1
    It's not an issue specific to lambdas, you always need std::ref if a thread parameter is a reference type, see http://stackoverflow.com/questions/36341724/c-thread-taking-reference-argument-failed-compile – zett42 Feb 20 '17 at 09:01

0 Answers0