是否可以编写一个 C++ 模板owner_of<...>
,使得给定以下代码:
struct X { int y; }
owner_of<&X::y>::type
是X
?
是否可以编写一个 C++ 模板owner_of<...>
,使得给定以下代码:
struct X { int y; }
owner_of<&X::y>::type
是X
?
你几乎可以做到这一点(或者至少到目前为止我找不到更好的解决方案):
#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" );
}