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
For me it looks like the first two print the type for const char*
, but the last one is an array.
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.: tests are done using Clang version 8.0.0-3 (tags/RELEASE_800/final) on Ubuntu 19.04.
The typeid operator provides a program with the ability to retrieve the actual derived type of the object referred to by a pointer or a reference. This operator, along with the dynamic_cast operator, are provided for runtime type identification (RTTI) support in C++.
The typeid operator allows the type of an object to be determined at run time. The result of typeid is a const type_info& . The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.
The typeid operator returns an lvalue of type const type_info that represents the type of our value.
typeid operator syntaxThe typeid operator requires RunTime Type Identification (RTTI) to be generated, which must be explicitly specified at compile time through a compiler option. The typeid operator returns an lvalue of type const std::type_info that represents the type of expression expr.
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++?.
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 );
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*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With