无法将const应用于typedef引用 [英] Cannot apply const to typedef reference

查看:60
本文介绍了无法将const应用于typedef引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在将 const 应用于 value_type& 的返回值引用时有效,但是如果我使用

The following code works when applying const to a return value reference of value_type& but errors if I use a typedef of the same type.

例如:

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 类。这与错误无关。

My actual code uses templates but I've removed for the example and substituted class T instead. This has no bearing on the error.

我不明白为什么在指定 value_type&

I don't see why this won't work if specifying value_type& instead compiles fine.

推荐答案

这里有两个不同的问题。

There are two different issues here.

首先,在以下位置:

typedef T* pointer;
typedef const pointer const_pointer;

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

the type of const_pointer is actually T* const, not const T*. The constness attaches to the pointer, not to the type pointed to.

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

Now references obey the same logic: if you make a typedef for the reference type, and try to attach const to it, it will try to apply the const to the reference type, not the referenced type. But references, unlike pointers, are not allowed to have top-level cv-qualification. If you try to mention T& const, it's a compilation error. But if you try to attach the cv-qualification through a typedef, it's just ignored.


Cv限定的引用格式错误,除非通过使用 typedef-name (7.1.3,14.1)或* decltype-specifier *(7.1.6.2)为cv限定词引入
,在这种情况下,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)

([dcl.ref]/1)

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

So the second issue is that GCC thinks this is an error, whereas the standard clearly states that it should not be an error, it should just ignore the const. I think this is a bug in GCC. Clang does not produce an error: http://coliru.stacked-crooked.com/a/5b5c105941066708

这篇关于无法将const应用于typedef引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆