0

Suppose I'm writing the following templated function:

class A { /* ... */ };

// ... etc...

template<typename C>
void foo() {
    bool C_inherits_A = /* magic */;
    if (C_inherits_A) { do_something(); }        
    else { do_something_else(); }
}

We remember dynamic_cast from the olden days, but that isn't relevant here since there's no pointer, and I'm checking "downward", not "upward". Is there something simple with which to replace /* magic */ in the snippet above?

PS - There should definitely already be a dupe of this question, but I just could not find one so I wrote it up.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

3

Beginning in C++11, the standard C++ library caters to this exact need - using the std::is_base_of type trait. To read a bit more about type traits see their SO tag page.

Anyway, you would replace /* magic */ with:

std::is_base_of<A, C>::value

which is a Boolean expression that's true if A is a base class of C, i.e. if C inherits A.

Remember that type traits are evaluated at compile-time, so you can use if (std::is_base_of<A,C>::value) in constexpr functions, or in template parameters and so on.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
einpoklum
  • 118,144
  • 57
  • 340
  • 684