【发布时间】:2013-11-23 23:35:43
【问题描述】:
我正在尝试使用 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;
X x(i);
modify_const(x);
std::cout << i << std::endl;
return 0;
}
如 cmets 中所述,只有最后一个注释版本的 acc() 有效,而使用其他代码,代码只是编译并打印值 1。
问题:我们如何使用基于decltype的新函数声明语法来定义acc()函数,使得这里的编译由于在@中返回const &int而失败987654328@,或者换句话说,acc() 有一个正确的const &int 返回类型。
备注:使用int i; 而不是int &i; 作为X 中的成员变量会产生编译错误,正如预期的那样。
编辑以更好地区分 v 和 X::i 的常量。我试图在acc() 中强加后者。
【问题讨论】:
标签: c++ c++11 constants decltype type-deduction