Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can pointers on std::type_info be compared for equality in constant expressions?

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

like image 825
Fedor Avatar asked Sep 27 '21 06:09

Fedor


People also ask

How to compare pointers of the same type for equality?

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.

How to compare pointers to objects of the same type?

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.

What is a const pointer?

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 *.

What is the difference between a variable and a constant pointer?

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.


Video Answer


1 Answers

This is a GCC bug: 85428

By the way, pType<int> == pType<int> is not always guaranteed.

like image 152
xskxzr Avatar answered Oct 23 '22 07:10

xskxzr