c++ - 自动返回类型不推导引用

标签 c++ c++11 auto return-type-deduction

我有以下代码:

#include <iostream>

struct C {
    int a;
    int& get() { return a; }
};
struct D {
    int a;
    int get() { return a; }
};
template <typename T>
auto foo(T o) { // no sample code is complete without a foo
    return o.get();
}

int main()
{
    C c;
    D d;
    c.a = 2;
    d.a = 42; // no sample code is complete without a 42
    std::cout << "c=" << c.a << ", d=" << d.a << "\n";
    c.get() = 3;
    //d.get() = 43;
    std::cout << "c=" << c.a << ", d=" << d.a << "\n";
    foo(c) = 4;  // <--- why won't this work?
    //foo(d) = 44;
    std::cout << "c=" << c.a << ", d=" << d.a << "\n";
}

为什么标记为编译的行不会?似乎编译器正在推导出 foo<C> 的返回类型成为int而不是 int&我会期待。为什么会这样,我怎样才能让它也推导出引用?

http://coliru.stacked-crooked.com/a/6ab909680836fd24

最佳答案

给定 auto,它被声明为非引用,所以我们正在处理按值传递的情况。和 auto遵循 template argument deduction 的规则; int& 的引用部分将被忽略,则推导类型为int

您可以使用 decltype(auto) (C++14 起)代替。

type is decltype(e), where e is the initializer.

template <typename T>
decltype(auto) foo(T&& o) { // no sample code is complete without a foo
    return o.get();
}

返回类型推导为decltype(o.get()),并根据decltype的规则,

if the value category of expression is lvalue, then decltype yields T&;

c.get()返回int&,它是一个左值,然后我们得到int的返回类型int&

顺便说一句:请注意,如果 o 仍按值传递,则返回的引用将悬空。

关于c++ - 自动返回类型不推导引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56429977/

相关文章:

c++ - 在 C++ 中定义常量 C 字符串的正确方法?

c++ - 调用Lua函数时的LuaBind C++错误处理程序

c++ - cvCalcOpticalFlowHS() opencv 抛出异常

"thread barrier"同步模式上的 C++ 正确原子内存排序

c++ - 为什么编译器不能通过逗号运算符扩展可变参数模板的参数?

c++ - 如何解决不明确的重载函数调用?

c++ - 带有引用的自动关键字行为

c++ - 如何创建对象变量以便每次都分配新的指针?

c++ - 可以在可变参数模板中推导出容器类型吗?

if-else 中的 C++11 lambda 函数定义