我正在尝试使用decltype了解C ++ 11中基于尾随返回的新函数声明语法。
在下面的代码,我试图定义一个成员函数返回一个const&允许只读访问到i
#include <iostream>
#include <type_traits>
struct X {
int &i;
X(int &ii) : i(ii) {}
// auto acc() const -> std::add_const<decltype((i))>::type { return i; } // fails the constness test
auto acc() const -> decltype(i) { return i; } // fails the constness test
// const int &acc() const { return i; } // works as expected
};
void modify_const(const X &v) {
v.acc() = 1;
}
int main() {
int i = 0; …Run Code Online (Sandbox Code Playgroud)