Search code examples
c++c++11vectorinitializer-liststd-function

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?


Solution

  • 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>>.