c++ - How do I check if two types have the same bit pattern and type? -
c++ - How do I check if two types have the same bit pattern and type? -
suppose have 3 types, a
, b
, int
. want know if combination of instantiations of these types have same content of bits. know nil a
or b
contain, , don't care. want know if they're same type , have same bit pattern.
for example:
struct { int a{2}; }; struct b { b() { int x = 2; b = *reinterpret_cast<double*>(&i); } double b; } template <typename t1, typename t2> bool issame(const t1& t1, const t2& t2) { homecoming t1 == t2; // won't work... no '==' operator! }; int main() { a; b b; a2; a2.a = 1; int c = 2; issame(a, a); // true issame(a, b); // false though , b have same bit pattern. issame(a, a2); // false because a2 contains "2" issame(a, c); // false because they're different types }
how implement issame
?
to check if 2 objects have identical representation can write:
if ( 0 == std::memcmp(&t1, &t2, sizeof t1) )
be aware of bits of object may not participate in value representation; and/or there may multiple possible representations same value; objects compare equal via operator==
may appear unequal using method.
you should add together in check sizeof t1 == sizeof t2
, can done @ compile-time.
c++
Comments
Post a Comment