我正在制作一个 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 );
在这种情况下,T
是 const 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/