我有以下代码:
#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&
我会期待。为什么会这样,我怎样才能让它也推导出引用?
最佳答案
给定 auto
,它被声明为非引用,所以我们正在处理按值传递的情况。和 auto
遵循 template argument deduction 的规则; int&
的引用部分将被忽略,则推导类型为int
。
您可以使用 decltype(auto)
(C++14 起)代替。
type is
decltype(e)
, wheree
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/