c++ - 在 std::function 中返回初始值设定项列表而不是 vector

标签 c++ c++11 vector initializer-list 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

让我们以这四种情况为例:

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::functioninitializer-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/

相关文章:

c++ - 补码查找算法

c++ - 隐式转换为左值引用

c++ - 尝试执行 shared_ptr swap() 时出现奇怪错误

python - 如何生成随机值的N维数组?

C++ 二维 vector 声明

c++ - 为什么我无法使用 OpenCV 获得正确的轮廓区域?

c++ - 读出数组元素会返回奇怪的数字;

c++ - 对同一数据使用两个不同的结构

c++ - STL map<string, string>,给key赋0值导致编译错误

c++ - 删除 vector vector 中的重复 vector