Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::is_same false for subclasses?

Why isn't subclass B the same as base class A?

I know B is A but A isn't B, but if is_same doesn't return true for these cases then I feel its use is limited.

Is there a std function that could return true in this case?

like image 589
DeepDeadpool Avatar asked Oct 18 '25 16:10

DeepDeadpool


1 Answers

Because is_same checks for the same type, and B is not the same type as A. What you want is is_base_of. Also these are metafunctions, not functions, and are more commonly referred to as type traits.

We can verify this with a simple program:

struct A {};     
struct B : A {};

int main()
{
    std::cout << std::boolalpha
      << std::is_same<A, A>::value << ' '        // true
      << std::is_same<A, const A>::value << ' '  // false!
      << std::is_same<A, B>::value << ' '        // false
      << std::is_base_of<A, B>::value << ' '     // true
      << std::is_base_of<B, A>::value << ' '     // false
      << std::is_base_of<A, A>::value << ' '     // true!
      << std::endl;
}

As TC points out in the comments, is_base_of also considers inaccessible/ambiguous bases, so perhaps you might also want to consider is_convertible, which does not. Example:

struct B { };
struct D : private B { };

int main()
{
    std::cout << std::boolalpha
        << std::is_base_of<B, D>::value << ' '   // true
        << std::is_convertible<D*, B*>::value    // false, because private
                                                 //   inheritance
        << std::endl;
}
like image 182
Barry Avatar answered Oct 20 '25 07:10

Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!