Reputation: 97691
Is it possible to write a C++ template owner_of<...>
such that given this code:
struct X { int y; }
owner_of<&X::y>::type
is X
?
Upvotes: 1
Views: 121
Reputation: 126562
You can almost do that (or at least I could not find a better solution so 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 you mind the use of decltype
, maybe a macro could 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" );
}
Upvotes: 1