Dynamic base class compilation time

Note that this is only a question of template syntax, not an object-oriented object-oriented polymorphism design. This example is a manufacture for this purpose.

Let's say I have a base class:

class A: public B
{
...
};

I use it ...

A a;
a.DoSomething();

What if I would like to do something like this to be able to generate A at compile time not only from B, but also from other classes. So that I can use it like this:

A<B> a;                // like class A : public B
a.doSomething();

A<C> ac;              // like class A : public C
ac.DoSomething();

Can I do something like this?

template <typename BASECLASS>
class A : public BASECLASS
{
...
};

Suppose my constructor had a parameter, and I knew that any template that I use for the hte base class has the same signature. If so, this is a * .h file, what do you do with a * .cpp file? Is it legal to initialize a constructor?

A::A(int param) : BASECLASS(param)
{

}

, - - ++, .

+4
2

. .

template <class Base>
class A : public Base {

};

class B {
public:
  void doSomething() {}
};
class C {
public:
  void doSomething() {}
};

int main() {
  A<B> a;                // like class A : public B
  a.doSomething();

  A<C> ac;              // like class A : public C
  ac.doSomething(); 
}
+1

, ++ 11 :

template <typename T>
class A: public T {
public:
    template <typename... Args>
    explicit A(Args&&... args): T(std::forward<Args>(args)...) {}

};

(typename...) (&& ), std::forward ; "" A .

0

All Articles