Ona*_*glu 5 c++ const decltype c++11 type-deduction
我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
如评论中所述,仅acc()作品的最后评论版本,而使用其他版本,代码仅编译并打印value 1。
问题:我们如何acc()使用基于的新函数声明语法来定义函数decltype,以使此处的编译由于返回const &intin modify_const或换句话说acc()具有正确的const &int返回类型而失败。
备注:按预期使用int i;而不是int &i;作为成员变量将X产生编译错误。
编辑更好地的常量性区分v,并X::i分别。我正试图强加于后者acc()。
问题是decltype((i))返回int&并应用于const该类型无效。你想要类似的东西
template <typename T> struct add_ref_const { typedef T const type; };
template <typename T> struct add_ref_const<T&> { typedef T const& type; };
Run Code Online (Sandbox Code Playgroud)
...然后使用
auto acc() const -> typename add_ref_const<decltype((i))>::type { return i; }
Run Code Online (Sandbox Code Playgroud)
也就是说,const需要介于type T和之间&。如果将const放置在正确的位置,则解决方案将是显而易见的:const应移至右侧。