Friday, 15 April 2011

templates - Is there any way to derive the object type from a member pointer type in C++ -



templates - Is there any way to derive the object type from a member pointer type in C++ -

is possible write c++ template owner_of<...> such given code:

struct x { int y; }

owner_of<&x::y>::type x?

you can almost (or @ to the lowest degree not find improve solution far):

#include <string> #include <type_traits> using namespace std; template<typename t> struct owner_of { }; template<typename t, typename c> struct owner_of<t (c::*)> { typedef c type; }; struct x { int x; }; int main(void) { typedef owner_of<decltype(&x::x)>::type should_be_x; static_assert(is_same<should_be_x, x>::value, "error" ); }

if mind utilize of decltype, maybe macro do:

#define owner_of(p) owner_of<decltype( p )>::type int main(void) { typedef owner_of(&x::x) should_be_x; static_assert(is_same<should_be_x, x>::value, "error" ); }

an alternative solution based on decltype:

template<typename t, typename c> auto owner(t (c::*p)) -> typename owner_of<decltype(p)>::type { } int main(void) { typedef decltype(owner(&x::x)) should_be_x; static_assert(is_same<should_be_x, x>::value, "error" ); }

c++ templates c++11 metaprogramming

No comments:

Post a Comment