c++ - typeid ("") != typeid(const char*)

标签 c++ c++17 rtti string-literals

我正在制作一个 C++ 库,它严重依赖 RTTI(可自定义桥接至另一种语言)并且对字符串文字类型非常困惑。

这是我为说明问题所做的一个简单测试:

std::cout << typeid(const char*).name() << std::endl; // PKc
std::cout << std::any("").type().name() << std::endl; // PKc
std::cout << typeid("").name() << std::endl;          // A1_c

对我来说,前两个打印出 const char* 的类型,但最后一个是数组。

为什么 std::any("").type()typeid("") 的结果不同?有没有办法获得第一个行为,即使字符串文字的结果一致(我使用类型标识来调用不同的类型处理程序)?

P.S.:测试是在 Ubuntu 19.04 上使用 Clang 版本 8.0.0-3 (tags/RELEASE_800/final) 完成的。

最佳答案

正如其他人提到的,字符串文字的类型 ""const char[1] ,如 What is the datatype of string literal in C++? 所解释的那样.

存储在 std::any("") 中的类型是 const char*因为您使用的是以下构造函数(http://www.eel.is/c++draft/any.cons#8):

// Effects: Constructs an object of type any that contains an object of 
// type std::decay_t<T> direct-initialized with std::forward<T>(value).
template< class T>
any( T&& value );

在这种情况下,Tconst char(&)[1] (字符串文字的类型 "" ),因此 std::decay_t<const char(&)[1]> 会给你const char* ,这就是为什么 typeid()std::any("").type()const char* 的类型 ID .

关于c++ - typeid ("") != typeid(const char*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56564321/

相关文章:

c++ - 在 LLVM JIT 代码中启用 RTTI 的问题

html - CppCMS 支持 unicode 吗?

java - 在 Java/PHP/Python 框架内运行已编译的 C/C++ 代码中的算法?

c++ - 额外的静态数组破坏了 omapl138 目标 (ccs5.2) 上的 DSP 应用程序

c++ - 标准变体和前向声明

c++ - 在微服务C++中运行gRPC服务器

c++ - 如何通过c中的指针传递二维数组

c++ - 如何从预处理程序#if指令调用constexpr函数?

c++ - 是否可以在 C++ 运行时告诉容器的值类型?

delphi - RTTI Delphi 创建一个 n 维矩阵作为 TValue