Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over all subclasses of a C++ class (at compile time)?

I want to generate a test case which asserts that a virtual method fulfills certain properties for all subclasses. How can I automate this?

class A {
 virtual int foo() = 0;
};

class B : public A {
 virtual int foo() override;
};

class C : public A {
 virtual int foo() override;
};

I want to do something like (I know the syntax below is rubbish)

for (A : SUBCLASSES_OF(A))
{
  A a;
  assert(a.foo() == 42);
}

Is that even possible with boost/template meta-programming/macro magic, or am I making a huge error in reasoning here?

like image 448
user1101674 Avatar asked Dec 09 '25 00:12

user1101674


2 Answers

What about a vistor? See Vistor Design Pattern. Also this answer is probaly helpful How Visitor Pattern avoid downcasting.

like image 109
Lars Avatar answered Dec 11 '25 14:12

Lars


That is impossible to do. Consider that the set of classes that extend a given base will probably be unknown when you compile the code you want. In particular, there nothing that blocks you or any other developer from adding a new class after your translation unit is compiled, and now 'compile time' of your translation and 'compile time' for your whole project would be different times.

The better question is what do you really want to solve?

like image 45
David Rodríguez - dribeas Avatar answered Dec 11 '25 14:12

David Rodríguez - dribeas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!