考虑这个片段:
#include <stdexcept>
template <typename T> class MyClass;
template <typename T> struct MyClass<T &> {
constexpr T &foo() && {
return value != nullptr ? std::move(*value)
: throw std::runtime_error("foo");
}
constexpr decltype(auto) bar() && {
return value != nullptr ? std::move(*value)
: throw std::runtime_error("bar");
}
T *value;
};
int main() {
const int &good = MyClass<int &>{}.bar();
const int &bad = MyClass<int &>{}.foo();
}
为什么decltype(auto)
方法中的返回规范bar
有效,而无效?T&
foo