gpt4 book ai didi

存储 type_info 对象的 C++ 方法不起作用

转载 作者:太空狗 更新时间:2023-10-29 20:24:47 25 4
gpt4 key购买 nike

我在理解 typeid 的返回类型与实际 type_info 对象之间的对应关系时遇到了一些麻烦,这些对象的工作方式似乎与通常的对象不同。例如,我可以...

std::cout << typeid(int).name() << std::endl;

...并从程序中获得良好的行为...但这不会编译...

std::type_info a(int);
std::cout << a.name() << std::endl;

编译器输出:

type_info.cpp: In function 'int main()':
type_info.cpp:6:17: error: request for member 'name' in 'a', which is of non-class type 'std::type_info(int)'

...我也做不到...

if(a == typeid(int)) {/*Do something*/ } //Looong error message

我错过了什么?

最佳答案

首先,令人烦恼的解析:

std::type_info a(int);

a 是一个函数(获取 int 并返回 std::type_info)。

其次,std::type_info 不可复制,因此您不能按值存储它。如果适合您的需要,您可以使用引用:

const std::type_info &a(typeid(int));

如果您需要实际存储 std::type_info 对象(好像)“按值”,请使用 std::type_index反而;它是为此而设计的:

std::type_index a(typeid(int));
std::cout << a.name() << std::endl;

关于存储 type_info 对象的 C++ 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26301024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com