C ++ Cannot convert lambda to std :: packaged_task to std :: pair

I did some testing with help std::packaged_taskand ran into this problem.

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

compiles and calls task()causes a 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, compiles:

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

Why can not I create pair?

+4
source share
1 answer

This constructor is an explicit constructor. You need to explicitly call it 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; } });

vector , emplace_back value_type. push_back, .

+5

All Articles