C++ 常量成员函数中成员变量的类型

C++ 常量成员函数中成员变量的类型,c++,constants,type-deduction,C++,Constants,Type Deduction,当我将一个成员函数标记为const并检查成员变量的类型时,我得到了一些意想不到的结果 #include <iostream> #include <string> template<typename T> struct type_printer; class const_type_test { public: void test() const { type_printer<decltype(value)> _;

当我将一个成员函数标记为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;
}
#包括
#包括
模板
结构式打印机;
类常量类型测试{
公众:
void test()常量{
打印机类型;
}
int&test2()常量{
返回值;
}
void test3()常量{
auto&x=值;
打印机类型;
}
void test4()常量{
自动*x=&value;
打印机类型;
}
私人:
int值;
};
int main(int argc,字符**argv)
{
常量常量类型测试x;
返回0;
}
我的理解是,当你在一个const方法中时,这个方法实际上是一些名称被破坏的名称,然后它们的参数类型是classname const*const。我一直认为,在const方法范围内,成员变量实际上是const,即值应该是const int。但是,当使用编译器错误来推断我得到的类型时,我没有预料到

#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;
}
void const_type_test::test()const
:aggregate
type_printer
的错误输出类型不完整,无法定义,
type_printer

因此,我看到类型被推断为int。我认为它将是const int,因为您不能更改值。我使用decltype错误吗?或者我的理解有漏洞

我想询问的原因是,在
test2
中,编译器抱怨:将
int&
类型的引用绑定到
const int
会丢弃限定符。这正是我所期望的。可以将常量引用绑定到非常量引用

示例3显示以下错误:错误:聚合
type\u打印机
的类型不完整,无法定义
type\u打印机
。这就是我所期望的,它被推断为常数参考

示例4:还推断出一个
type_打印机
,我认为它是一个指针


渴望得到一些参考标准,以找出我知识中的漏洞。我还想知道,在使用
decltype
时,是否有一些奇怪的类型推断规则让我大吃一惊。

decltype
对类成员有特殊的规则。它返回成员的实际类型。如果你想用代码> DECKType 考虑上下文(const函数内),那么你可以把表达式包在括号内。

没有偏执:

 void test() const {
        type_printer<decltype(value)> _;
    }
 void test() const {
        type_printer<decltype((value))> _;
    }

void test()常量{
打印机类型;
}
c.cpp:10:39:错误:未定义模板“type\u printer”的隐式实例化
打印机类型;
有妄想症:

 void test() const {
        type_printer<decltype(value)> _;
    }
 void test() const {
        type_printer<decltype((value))> _;
    }

void test()常量{
打印机类型;
}
c.cpp:10:41:错误:未定义模板“type\u printer”的隐式实例化
打印机类型;
参考:

如果参数是一个未授权的id表达式或一个未授权的类成员访问表达式,则decltype将生成由该表达式命名的实体类型。如果没有这样的实体,或者参数命名了一组重载函数,则程序的格式不正确

如果expression参数是标识符或类成员访问,则decltype(expression)是由expression命名的实体的类型。如果没有这样的实体或表达式参数命名一组重载函数,编译器将生成错误消息


确保您使用的是正确的类型。某些类型的范围比其他类型的范围小

此特殊规则也适用于正则变量。