相关疑难解决方法(0)

如果返回一个向量项,那么lambda表达式的返回类型是什么?

请考虑以下代码段:

#include <iostream>
#include <vector>
#include <functional>

int main() 
{
    std::vector<int>v = {0,1,2,3,4,5,6};
    std::function<const int&(int)> f = [&v](int i) { return v[i];}; 
    std::function<const int&(int)> g = [&v](int i) -> const int& { return v[i];};

    std::cout << f(3) << ' ' << g(3) << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我期待相同的结果:in f,v由const引用传递,所以v[i]应该有const int&类型.

但是,我得到了结果

 0 3
Run Code Online (Sandbox Code Playgroud)

如果我不使用std :: function,一切都很好:

#include <iostream>
#include <vector>
#include <functional>

int main() 
{
    std::vector<int>v = {0,1,2,3,4,5,6};
    auto f = [&v](int i) …
Run Code Online (Sandbox Code Playgroud)

c++ lambda c++11 std-function return-type-deduction

27
推荐指数
3
解决办法
3320
查看次数

标签 统计

c++ ×1

c++11 ×1

lambda ×1

return-type-deduction ×1

std-function ×1