One can define a constexpr
pointer on std::type_info
object of any class T
. Does the language allows one to compare such pointers for equality in compile-time?
For example:
#include <typeinfo>
template <typename T>
inline constexpr auto * pType = &typeid(T);
int main() {
static_assert( pType<int> == pType<int> );
static_assert( pType<int> != pType<char> );
}
The question arises, since Clang accepts it, but GCC returns the error:
error: non-constant condition for static assertion
8 | static_assert( pType<int> != pType<char> );
| ~~~~~~~~~~~^~~~~~~~~~~~~~
<source>:8:31: error: '(((const std::type_info*)(& _ZTIi)) != ((const std::type_info*)(& _ZTIc)))' is not a constant expression
Demo: https://gcc.godbolt.org/z/9broYrEn7
From § 5.10 of the C++11 standard: Pointers of the same type (after pointer conversions) can be compared for equality. Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address ( 3.9.2 ). [...] If both operands are null, they compare equal.
Pointers to objects of the same type can be compared for equality with the 'intuitive' expected results: From § 5.10 of the C++11 standard: Pointers of the same type (after pointer conversions) can be compared for equality.
This type of pointer is essentially a combination of the two types discussed previously, i.e., a combination of constant pointer and a pointer to a constant. Note: It is necessary to initialize these types of pointers during declaration itself. Here, we have two const keywords in the syntax, one before and one after the *.
Although, the pointer itself can change and points somewhere else (as the pointer itself is a variable). In constant pointers, the pointer points to a fixed memory location, and the value at that location can be changed because it is a variable, but the pointer will always point to the same location because it is made constant here.
This is a GCC bug: 85428
By the way, pType<int> == pType<int>
is not always guaranteed.
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