当我将一个成员函数标记为const并检查成员变量的类型时,我会得到一些我不期望的结果。
#include <iostream>
#include <string>
template<typename T>
struct type_printer;
class const_type_test {
public:
void test() const {
type_printer<decltype(value)> _;
}
int& test2() const {
return value;
}
void test3() const {
auto& x = value;
type_printer<decltype(x)> _;
}
void test4() const {
auto* x = &value;
type_printer<decltype(*x)> _;
}
private:
int value;
};
int main(int argc, char** argv)
{
const const_type_test x;
return 0;
}
我的理解是,当您在const方法中时,方法实际上是某个名称,mangled name,然后它们的参数类型是classname const*const。 我一直认为在const方法作用域中,成员变量是有效的const,即value是const int。 然而,当使用编译器错误来推导类型时,我得到了我不期望的类型。
void const_type_test::test()const
:aggregetype_printer
类型不完整,无法定义,type_printer
所以我看到类型被推导为int。 我以为它是常量,因为你不能改变它的值。 我是不是用错了decltype? 或者我的理解力有漏洞。
我猜这样问的原因是,在test2
中,编译器会抱怨:将int&
类型的引用绑定到const int
会丢弃限定符。 这正是我所期望的。 可以将常量引用绑定到非常量引用。
示例3显示以下错误:错误:aggregetype_printer
类型不完整,无法定义type_printer
。 这是我所期望的,它已经被推演为一个常量的参考。
示例4:还推导了一个type_printer
,我认为它是一个指针。
渴望得到一些标准的参考,以找出我知识上的漏洞在哪里。 我也在想,在使用decltype
时,是否有一些怪异的类型推演规则正在让我绊倒。
const
函数中唯一改变的是this
指针的类型。
在常量
成员函数中,此
是常量CONST_TYPE_TEST*
类型。 在非常量
成员函数中,此
是CONST_TYPE_TEST*
类型。
在const
成员函数中,类似以下内容的编译
this->value = 0;
的显式形式
value = 0;
都会失败。
值
的类型没有差异。 它始终是int
。 &value
的类型始终是int*
。 我认为这正是问题所提出的误解的症结所在。