Other languages have an "is" operator that allow this, how do I emulate this in C and can it be done at runtime?
Say for example,
class A {
public:
// virtual methods..
};
class B : public A {};
class C: public A {};
A* x;
template<typename T>
bool foo(); // returns true if par is of type T
int main() {
A* b = new B();
A* c = new C();
x = c;
if(foo<B>(x))
{
// do something
}
}
CodePudding user response:
At runtime, you could dynamic_cast
and see if you have a nullpointer. A dynamic cast will return nullptr
at runtime if the input pointed type is not compatible with the output pointed type.
A* b = new B();
A* c = new C();
x = c;
if(dynamic_cast<B*>(x) != nullptr)
{
// do something
}
CodePudding user response:
You can just write
if (dynamic_cast<B*>(x)) {
// ...
}
since it returns nullptr
(which evaluates as false
) if the dynamic type doesn't match.
Note that this doesn't guarantee that B
is the most-derived type, only that it is an accessible base class of the most-derived type.
Since you actually asked how to write the function foo
, it's simply
template<typename Dynamic, typename Static>
bool foo(Static *p)
{
return dynamic_cast<Dynamic*>(p);
}
but this isn't very interesting, and the foo<B>(x)
call is less clear at the call site - to an experienced C developer - than just writing the dynamic_cast
directly.
NB. The comments suggesting that this is usually a bad idea are correct - it's generally better to use virtual dispatch to handle this kind of thing automatically.