是否可以编写一个C ++模板owner_of<...>
,以便给出以下代码:
struct X { int y; }
owner_of<&X::y>::type
是X
?
答案 0 :(得分:1)
你几乎这样做(或者至少到目前为止我找不到更好的解决方案):
#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" );
}
如果您介意使用decltype
,也许宏可以这样做:
#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" );
}
基于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" );
}