Reputation:
Consider the following class hierarchy with CRTP:
template <class T>
struct BaseClass {
void foo_interface(int a) {
static_cast<T*>(this)->foo(a);
}
};
struct SubClass1 : public BaseClass<SubClass1> {
void foo(int a) { std::cout << "SubClass1\n"; }
};
struct SubClass2 : public BaseClass<SubClass2> {
void foo(int a) { std::cout << "SubClass2\n"; }
};
int main(int argc, char* argv[]) {
BaseClass<SubClass1>* b1 = new SubClass1();
BaseClass<SubClass2>* b2 = new SubClass2();
b1->foo_interface(3); // Print "SubClass1"
b2->foo_interface(4); // Print "SubClass2"
delete b1;
delete b2;
}
I need to create a SuperClass of BaseClass to obtain the same behaviour but in the following way (I have to iterate on a collections of object and call this method):
int main(int argc, char* argv[]) {
SuperClass* b1 = new SubClass1();
SuperClass* b2 = new SubClass2();
b1->foo_interface(3); // Print "SubClass1"
b2->foo_interface(4); // Print "SubClass2"
delete b1;
delete b2;
}
It is possible? I can't use virtual methods and I try to avoid function pointers. The method foo_interface can be also defined outside from all classes. These methods must be called a lot of times, thus i can't use switch/if constructs for performance reasons.
Upvotes: 0
Views: 116
Reputation: 146910
You can't have a run-time interface without run-time dispatch (which you have banned). Therefore, it's impossible for you to do what you want. If you want a run-time interface, you need run-time dispatch through say function pointers or virtual functions.
You could also consider putting the different subclasses in different collections.
Upvotes: 3