A
AdlerSam
Hi,
I try to understand static polymorphism in the context of the
curiously recurring template pattern, but fail desperately to catch
the point.
Please have a look at the following code:
#include <iostream>
using namespace std;
template <class Derived> struct Base {
void interface() {
static_cast<Derived*>(this)->implementation();
}
};
struct Derived1 : Base<Derived1> {
void implementation() {cout << "Derived1 member" << endl;}
};
struct Derived2 : Base<Derived2> {
void implementation() {cout << "Derived2 member" << endl;}
};
int main() {
Base<Derived1> *x;
x = new Derived1();
x->interface();
// I can't assign a Derived2 instance to x!?
return 0;
}
To me, polymorphism means that it should be possible to assign either
an instance of Derived1 or Derived2 to the _same_ variable (x in the
example), and then, when calling a member fuction through x (i.e.
interface()), having the right implementation being run.
Can anyone help me showing where I'm off the track?
I try to understand static polymorphism in the context of the
curiously recurring template pattern, but fail desperately to catch
the point.
Please have a look at the following code:
#include <iostream>
using namespace std;
template <class Derived> struct Base {
void interface() {
static_cast<Derived*>(this)->implementation();
}
};
struct Derived1 : Base<Derived1> {
void implementation() {cout << "Derived1 member" << endl;}
};
struct Derived2 : Base<Derived2> {
void implementation() {cout << "Derived2 member" << endl;}
};
int main() {
Base<Derived1> *x;
x = new Derived1();
x->interface();
// I can't assign a Derived2 instance to x!?
return 0;
}
To me, polymorphism means that it should be possible to assign either
an instance of Derived1 or Derived2 to the _same_ variable (x in the
example), and then, when calling a member fuction through x (i.e.
interface()), having the right implementation being run.
Can anyone help me showing where I'm off the track?