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
让我们以这四种情况为例:
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};
};
为什么 4 不能接受,因为 2 是可以接受的?他们之间有什么不同?而且,最奇怪的是,这是可以接受的:
//Acceptable
auto bar=[]()->std::vector<int>{
return {1};
};
std::function
和 initializer-list
有什么问题?
最佳答案
auto bar=[]()->std::vector<int>{
指定 lambda 的返回类型 bar
成为std::vector<int>
.
std::function<std::vector<int>()> foo=[](){
没有指定 foo
的返回类型,因为您首先推断出 lambda 的返回类型,然后对其进行分配。
C++ 在决定类型时不考虑您可以将 lambda 分配给什么,它看到返回 {1},这是一个 std::initializer_list<int>
, 这与 std::function<std::vector<int>>
不兼容.
关于c++ - 在 std::function 中返回初始值设定项列表而不是 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37895252/