有没有办法从C ++中的成员指针类型派生对象类型

时间:2013-02-19 17:17:10

标签: c++ templates c++11 metaprogramming

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

struct X { int y; }

owner_of<&X::y>::typeX

1 个答案:

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