mercredi 16 avril 2014

c ++ 11 - force C++ substituer - Stack Overflow


I have some class, like


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

It provides some interface, and I want all derivated to override method name. Problem is, it is not overriden, nothing breaks at compile time, but I get problems in run-time. Is it any way to enforce method overriding? EDIT: I want to enforce overriding in all derivates, not just direct descedants!




You can check whether a member is defined in a base class by checking its pointer-to-member type:


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

This does mean that at compile time you must have access to all the descendant types that you're interested in.




Yes, make it a pure virtual:


constexpr virtual std::string name() = 0;


I have some class, like


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

It provides some interface, and I want all derivated to override method name. Problem is, it is not overriden, nothing breaks at compile time, but I get problems in run-time. Is it any way to enforce method overriding? EDIT: I want to enforce overriding in all derivates, not just direct descedants!



You can check whether a member is defined in a base class by checking its pointer-to-member type:


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

This does mean that at compile time you must have access to all the descendant types that you're interested in.



Yes, make it a pure virtual:


constexpr virtual std::string name() = 0;

0 commentaires:

Enregistrer un commentaire