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 aninitializer-list
. I want to fill the returnedstd::vector
byinitializer-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
?
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>>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With