typeid(“")!= typeid(const char *) [英] typeid("") != typeid(const char*)

查看:101
本文介绍了typeid(“")!= typeid(const char *)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个C ++库,该库高度依赖RTTI(到另一种语言的可定制桥),并且对字符串文字类型非常困惑.

I'm making a C++ library which relies heavily on RTTI (customizable bridge to another language) and is very confused about string literal type.

这是我做的一个简单测试,用于显示问题:

This is a simple test I made to show the problem:

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 * 的类型,但最后一个是数组.

For me it looks like the first two print the type for const char*, but the last one is an array.

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

Why do results for std::any("").type() and typeid("") differ? Is there a way to get the first behavior, i.e. make results for string literals consistent (I use type identification to call different type handlers)?

P.S .:在Ubuntu 19.04上使用Clang版本8.0.0-3(标签/RELEASE_800/final)进行测试.

P.S.: tests are done using Clang version 8.0.0-3 (tags/RELEASE_800/final) on Ubuntu 19.04.

推荐答案

正如其他人提到的那样,字符串文字" 的类型为 const char [1] ,例如所解释的那样,字符串文字的数据类型是什么在C ++中?.

As others have mentioned, the type of the string literal "" is const char[1], as explained by, e.g., What is the datatype of string literal in C++?.

存储在 std :: any(")中的类型为 const char * ,因为您正在使用以下构造函数(

The type stored in std::any("") is const char* because you are using the following constructor (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 * ,这就是为什么 std :: any(").type的 typeid()的原因() const char * 的类型ID.

In this case, T is const char(&)[1] (the type of the string literal ""), and thus std::decay_t<const char(&)[1]> will give you const char*, which is why the typeid() of std::any("").type() is the type ID of const char*.

这篇关于typeid(“")!= typeid(const char *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆