May I know if a polymorphic object implements an arbitrary abstract class?

This question came up in a class I attended. Consider:

class foo{virtual void foo_fun() = 0;};

class bar{virtual void bar_fun() = 0;};

template<typename T>
bool is_a_bar(T* f) {
    // I don't know baz.
    // Can I somehow know if f implements bar, T being any other type?
}

class baz : public foo, public bar {
    void foo_fun() override {}
    void bar_fun() override {}
};

#include <iostream>

int main() {
    foo* a{new baz};
    if (is_a_bar(a))  // Will call is_a_bar(foo*)
        std::cout << "a is also a bar\n";
}

      

Is it possible to know if an arbitrary object derived from foo

or bar

, also from another ... without knowing what the actual object is?

(Suppose I cannot change foo

or bar

to provide this information.)

+3


source to share


2 answers


I have to admit that I'm not entirely sure if this is what you are looking for, but you can downsize the mentioned function to only play with polymorphic classes using SFINAE and use what you are looking dynamic_cast<>

for to query.

Something like:

template<typename T>
typename std::enable_if<std::is_polymorphic<T>::value,bool>::type
is_a_bar(T* f)
{
    return dynamic_cast<bar const*>(f) != nullptr;
}

      



Any use of void*

or some non-polymorphic T

will get confusing at compile time (and this obviously includes void

).

Good luck.

+6


source


If you compile your code with RTTI, you can use dynamic_cast:



template<typename T>
bool is_a_bar(T* f) {
    return dynamic_cast<bar*>(f) != nullptr;
}

      

+5


source







All Articles