Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return initializer list instead of vector in std::function

Edit: It is not duplicated of the linked question (which is mine also). Here all the return types are std::vector. I do not want to return an initializer-list. I want to fill the returned std::vector by initializer-list directly

Let us take those four cases:

1)

//Acceptable
std::vector<int> foo(){
    return std::vector<int>{1}; 
}

2)

//Acceptable
std::vector<int> foo(){
    return {1};    
}

3)

//Acceptable
std::function<std::vector<int>()> foo=[](){
    return std::vector<int>{1}; 
};

4)

//NOT Acceptable
std::function<std::vector<int>()> foo=[](){
    return {1}; 
};

Why 4 is not acceptable since 2 is acceptable? what is the different between them? Moreover, the most strange thing that this is acceptable:

//Acceptable
auto  bar=[]()->std::vector<int>{
    return {1}; 
};

What is wrong with std::function and initializer-list?

like image 479
Humam Helfawi Avatar asked Jun 18 '16 09:06

Humam Helfawi


1 Answers

auto bar=[]()->std::vector<int>{ specifies the return type of the lambda bar to be std::vector<int>.

std::function<std::vector<int>()> foo=[](){ does not specify the return type of foo, because you first deduce the return type of the lambda, then assign it.

C++ does not take into account what you may assign the lambda to when deciding on a type, it sees return {1}, which is an std::initializer_list<int>, which is incompatible with a std::function<std::vector<int>>.

like image 184
nwp Avatar answered Sep 19 '22 12:09

nwp