Reputation: 1212
We have a method which is being passed a class as an argument. This class has different child classes. We need to know which of those classes is the one who is being passed as an argument to this method. We can't define one method for each of the possible classes due to assignment requirements. Furthermore, if the child class isn't supported by this method, the error must be thrown in compile time. We've been trying to do this using static_cast but we are not obtaining the required results as the conversion between the two child classes is always possible.
class A{
...
};
class B : public A{
...
};
class C : public A{
...
}
void foo(A a){
if(a is B){
//OK and do stuff
}else if(a is C){
//throw compile error
}
}
Upvotes: 2
Views: 904
Reputation: 2015
You can write foo
itself as a template for doing all the checks at compile time:
#include <type_traits>
template<class T>
void foo(T t)
{
static_assert(std::is_same<T, C>::value == false,
"foo() must not be invoked with object of class C");
if (std::is_same<T, B>::value) {
// do stuff
}
}
static_assert
is used for compile time checks of some condition and std::is_same
compares two types at compile time.
Upvotes: 1