| 1 |
#include <iostream> |
| 2 |
|
| 3 |
using namespace std; |
| 4 |
|
| 5 |
class VehicleBase |
| 6 |
{ |
| 7 |
// original Vehicle members, not implementing the |
| 8 |
// redefinable interface, but used as a implementable rather than |
| 9 |
// instantiatable part of the corresponding class template. |
| 10 |
// That's why it declares its corresponding class template a friend. |
| 11 |
|
| 12 |
template <class Derived> |
| 13 |
friend class Vehicle; |
| 14 |
|
| 15 |
size_t d_massFactor = 1; |
| 16 |
}; |
| 17 |
|
| 18 |
template <class Derived> |
| 19 |
class Vehicle: public VehicleBase |
| 20 |
{ |
| 21 |
public: |
| 22 |
int mass() const |
| 23 |
{ |
| 24 |
return d_massFactor * |
| 25 |
static_cast<Derived const *>(this)->vmass(); |
| 26 |
} |
| 27 |
}; |
| 28 |
|
| 29 |
class CarBase: public VehicleBase |
| 30 |
{ |
| 31 |
// original Car members, not implementing the |
| 32 |
// redefinable interface |
| 33 |
|
| 34 |
int x = 1000; |
| 35 |
friend class Car; |
| 36 |
}; |
| 37 |
|
| 38 |
class Car: public CarBase, public Vehicle<Car> |
| 39 |
{ |
| 40 |
friend class Vehicle<Car>; |
| 41 |
|
| 42 |
int vmass() const |
| 43 |
{ |
| 44 |
return x; |
| 45 |
} |
| 46 |
}; |
| 47 |
|
| 48 |
class TruckBase: public CarBase |
| 49 |
{ |
| 50 |
// original Truck members, not implementing the |
| 51 |
// redefinable interface |
| 52 |
|
| 53 |
friend class Truck; |
| 54 |
}; |
| 55 |
|
| 56 |
class Truck: public TruckBase, public Vehicle<Truck> |
| 57 |
{ |
| 58 |
friend class Vehicle<Truck>; |
| 59 |
|
| 60 |
private: |
| 61 |
int vmass() const |
| 62 |
{ |
| 63 |
return 15000; |
| 64 |
} |
| 65 |
}; |
| 66 |
|
| 67 |
template <class Vehicle> |
| 68 |
void fun(Vehicle &vehicle) |
| 69 |
{ |
| 70 |
cout << vehicle.mass() << '\n'; |
| 71 |
} |
| 72 |
|
| 73 |
int main() |
| 74 |
{ |
| 75 |
Car car; |
| 76 |
fun(car); |
| 77 |
|
| 78 |
Truck truck; |
| 79 |
fun(truck); |
| 80 |
} |