This is a followup question of Static polymorphism with final or templates?. So it seems that the best solution for static-only polymorphism is to use CRTP. If you want runtime polymorphism, virtual functions are a good solution.
I find that not very elegant because the problems are actually very similar (and maybe you want to change the behavior at some point) but the code is actually very different. The code would in my opinion be more expressive if the solutions would be very similar and only differ at a single spot.
So I would like to know if there is a way to get static-only polymorphism with virtual functions. That might be something like an attribute or some construction to not allow pointers to the abstract base class. Is there such a feature and if not, am I missing something why such a feature should not exist? Are static and runtime polymorphism actually more different than such a feature would suggest?
EDIT: To make the question and the usecase a bit clearer, here is some example, that I would like to write:
[[abstract]] class Base {
public:
void bar() { /* do something using foo() */ }
private:
virtual void foo() = 0;
};
class Derived1 : public Base {
public:
Derived1();
private:
void foo() override { /* do something */};
};
class Derived2 : pulic Base {
public:
Derived2();
private:
void foo() override { /* do something with data */ }
int data;
};
where the non-existing attribute [[abstract]] means that there cannot exist an instance of the class Bass, even not by a pointer. This would clearly express static polymorphism and the compiler could optimize away virtual calls because they do not exist. Also a virtual destructor would not be necessary.
EDIT 2: The goal is to provide an abstract interface that can be slightly modified in further derived classes and has the same options for extending as an abstract class. So the main implementation is still in Base
and the specific implementation of the virtual functions is in Derived
.