C ++ Force Constraint

I have some class like

class object { public: virtual std::string name() const; }; 

It provides some interface, and I want all derivatives to override the name method. The problem is that it is not overestimated, nothing breaks during compilation, but I have problems at runtime. Is this a way to force method overrides? EDIT: I want forced control over all derivatives, not just direct descedants!

+4
source share
2 answers

You can check if an element is defined in the base class by specifying its type as a pointer to a member:

 static_assert(std::is_same<decltype(&U::name), std::string (U::*)()>::value, "name must be defined directly in U"); 

This means that at compile time you must have access to all types of descendants that interest you.

+6
source

Yes, make it pure virtual:

 constexpr virtual std::string name() = 0; 
+8
source

All Articles