typeid("") != typeid(const char*)
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*
.
Why do results for
std::any("").type()
andtypeid("")
differ?
Accroding to the following reference:
template< class ValueType > any( ValueType&& value );
4) Constructs an object with initial content an object of type
std::decay_t<ValueType>
, direct-initialized fromstd::forward<ValueType>(value)
.
std::decay_t<const char[1]>
is const char*
.
Here is a quote from FrankHB1989 on the isocpp.org forum, which I think is relevant in understanding std::any
, in context of this question:
[
std::any
] is even not for "any object". As I have argued before, I have expect the word "any" being short for "any first-class object type" (i.e. cv-unqualified non-array object type), butstd::any
has additional refinement of CopyConstructible on the value type, so it is actually for "any copyable cv-unqualified non-array object type" instead.
As such
Is there a way to get first behavior, i.e. make results for string literals consistent (I use type identification to call different type handlers)?
There is no way of having std::any
of array (you can have std::any
of std::array
, but string literal is not a std::array
), and there is no way of making typeid("")
be a pointer. However, you can use std::decay_t<decltype("")>
to get the same type as stored in std::any
.
It is a common misconception that a string literal has type const char*
.
It doesn't. It has type const char[<size + 1>]
(plus one for the null terminator).
e.g. ""
has type const char[1]
.
But we often assign a string literal to a const char*
, out of convention (and also because otherwise we trigger special rules that result in copying the string).
Furthermore, array name decay rules actually make it quite hard to observe the array-ness of a name in C (and, by extension, C++); that std::any
works the way it does is an example of that.