vendredi 24 novembre 2017

Using pointer to member function of a base class on object of derived class

Consider following code snippet:

struct Base {
    std::string foo () const { std::cout << "Base::foo()\n"; return "X"; }
};

struct Der : Base {};

struct Ptr : std::integral_constant<std::string (Base:: *) () const, &Base::foo> {};

and usage is like this:

Der der;
std::string s = (der.*Ptr::value) ();
std::cout << s << "\n";

Output is as desired:

Base::foo()
X

Everything seems to be fine.

My question is: Is this code correct? Or am I stepping on the land of undefined behavior? Can I use pointer to member function of a base class on object of derived class directly?

Aucun commentaire:

Enregistrer un commentaire