Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ future.get() return types

--Example Updated--

Here's a bit of code :

int retInt(int a) { return a; }
void randomFunction() 
{
    int a = 3;
    auto future = async([&]{ return retInt(a); });
    const auto ret = future.get();
}

VS2012 intellisense tells me that 'ret' is a const < error-type > and will not let me compile, giving me an output message of:

[cannot deduce type for 'const auto' from 'void']

If for example I change 'ret' from const auto to const int and specify an actual type everything compiles just fine, but I'm wondering why the auto version doesn't work and if there would be a possible code change of some sort to make a version with auto compile.

Any ideas?

Note:

Changing the

auto future = async([&]{ return retInt(a); });

to

auto future = async([&] ()->int{ return retInt(a); });

yields the same result

like image 271
dk123 Avatar asked Aug 26 '26 14:08

dk123


1 Answers

You have extra [] inside lambda expression, which makes an embedded lambda express. inner lambda returns 1 but outter lamda return type is not specified which is default to void.

change

auto afuture = async([&]{ []{ return 1; }; });

to:

auto afuture = async( []{  return 1; });
const auto ret = afuture.get();

Edit:

Your new code just works fine on VS2012 NOV CTP and gcc 4.7.2.

Note: you are capturing local variable a by reference, it's safe for async thread, you may want to capture it by value.

auto future = async([=]{ return retInt(a); });
                    ^^^

Sample code compiled:

http://liveworkspace.org/code/X66xE$2

like image 158
billz Avatar answered Aug 29 '26 04:08

billz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!