c++ - 无法将 const 应用于 typedef 引用

标签 c++ constants const-correctness

以下代码在将 const 应用于 value_type& 的返回值引用时有效,但如果我使用相同类型的 typedef,则会出错。

举个例子:

class T {
};

class A {
public:
    typedef T value_type;
    typedef value_type& reference;

    // Not working
    const reference operator*() const;

    // But this works?
    //const value_type& operator*() const;
};

// Error!
const typename A::reference A::operator*() const {
}

int main() {
    return 0;
}

g++ 会出错:

'const' qualifiers cannot be applied

我的实际代码使用模板,但我已经删除了示例并替换为类 T。这与错误无关。

如果指定 value_type& 编译正常,我不明白为什么这不起作用。

最佳答案

这里有两个不同的问题。

首先,在:

typedef T* pointer;
typedef const pointer const_pointer;

const_pointer的类型实际上是T* const,而不是const T*。 constness 附加到指针,而不是指向的类型。

现在引用遵循相同的逻辑:如果你为引用类型创建一个 typedef,并尝试将 const 附加到它,它会尝试将 const 应用到引用类型,而不是引用类型。但与指针不同,引用不允许具有顶级 cv 限定。如果您尝试提及 T& const,这是一个编译错误。但是,如果您尝试通过 typedef 附加 cv 限定,它就会被忽略。

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or *decltype-specifier *(7.1.6.2), in which case the cv-qualifiers are ignored.

([dcl.ref]/1)

所以第二个问题是 GCC 认为这是一个错误,而标准明确指出它不应该是一个错误,它应该忽略 const。我认为这是 GCC 中的错误。 Clang 不会产生错误:http://coliru.stacked-crooked.com/a/5b5c105941066708

关于c++ - 无法将 const 应用于 typedef 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35352168/

相关文章:

constants - D 中的逻辑常量

c++ - 如何正确声明从非常量迭代器到指针的常量指针

c++ - 为什么按降序排序与升序排序时快速排序需要更长的时间

c++ - 每次运行都从不同的文件中读取整数,为什么?

c++ - 如何选择一个类来动态实例化?

c - 理解函数(const int *a)指向整型常量的指针

java - 在计算中使用常量变量?

c++ - 使用常量是否节省内存

c++ - 在另一个类中实现一个类的对象

c++ - 为什么 shared_ptr<A> 不隐式转换为 shared_ptr<A const>?