5

I did some testing with std::packaged_task and came across this problem.

std::packaged_task<int(void)> task([]() -> int { return 1; }); task(); 

compiles and calling task() calls the lambda. However, this does not compile:

std::pair<int, std::packaged_task<int(void)>> pair(15, []() -> int { return 15; }); pair.second(); 

because

error C2664: 'std::pair<int,std::packaged_task<int (void)>>::pair(const std::pair<int,std::packaged_task<int (void)>> &)': cannot convert argument 2 from 'main::<lambda_abbe6cccb9110894d95e872872ec1296>' to 'const std::packaged_task<int (void)> &'

This, however, does compile:

std::vector<std::packaged_task<int()>> v; v.emplace_back([](){ return 1; }) 

Why can't I create a pair?

1 Answer 1

6

The constructor in question is an explicit constructor. You need to explicitly invoke it for this to compile:

std::pair<int, std::packaged_task<int(void)>> pair(15, std::packaged_task<int(void)>{ []() -> int { return 15; } }); 

Or, better yet, use std::make_pair:

auto pair = std::make_pair(15, std::packaged_task<int(void)>{ []() -> int { return 15; } }); 

The case with the vector works, because emplace_back forwards the arguments to the value_type's constructor. If you tried with push_back it wouldn't work.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.