使用 decltype 和 constness 的 C++11 尾随返回成员函数

标签 c++ c++11 constants decltype 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;
}

如评论中所述,只有最后评论的 acc() 版本有效,而使用其他版本时,代码仅编译并打印值 1

问题:我们如何使用基于decltype 的新函数声明语法来定义acc() 函数,这样由于在 modify_const 中返回了一个 const &int,或者换句话说,acc() 有一个合适的 const,这里的编译失败了&int 返回类型。

备注:使用int i;代替int &i;作为X中的成员变量会产生一个如预期的那样编译错误。

编辑以更好地区分 vX::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; };

...然后使用

auto acc() const -> typename add_ref_const<decltype((i))>::type { return i; }

也就是说,const 需要在类型T& 之间。如果您将 const 放入正确的位置,解决方案将很明显:const should go to the right .

关于使用 decltype 和 constness 的 C++11 尾随返回成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20169269/

相关文章:

C++ 2 <= n 的最大幂

Swift常量哪个更好?

c++ - 防止类被释放

c++ - 智能指针作为 QObject::deleteLater() 的替代品

c++ - 无论参数签名如何,我都可以制作一个函数表吗?

c - 将 const char * 传递给 C 中的函数

class - 创建一个不可实例化、不可扩展的类

c++ - deque.tcc 错误 : expected primary-expression before '>' token

c++ - 数组作为映射键

c++ - glDrawElements 中的索引参数是什么意思?