有没有任何方法可以从C++中的成员指针类型派生对象类型

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

本文关键字:类型 成员 指针 派生 对象 C++ 方法 任何 有没有      更新时间:2023-10-16

是否可以编写一个C++模板owner_of<...>,使得给定以下代码:

struct X { int y; }

owner_of<&X::y>::typeX

你几乎可以这样做(或者至少到目前为止我找不到更好的解决方案):

#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" );
}