是否可以编写这样的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" );
}
关于c++ - 有没有办法从C++中的成员指针类型派生对象类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14963502/