从指针到成员变量获取类和成员类型

Bil*_* Li 3 c++ boost

例如:

template <typename T>
void foo(T ptr)
{
  typedef GET_CLASS_TYPE(T) ClassT;
  typedef GET_VALUE_TYPE(T) ValueT;
  // ...
}

struct Bar
{
  int var;
};

foo(&Bar::var);  
Run Code Online (Sandbox Code Playgroud)

里面的最后一个函数调用foo(...),ClassT应该是BarValueTint.

如何使用普通C++(不能使用C++ 11功能)或者提升?

mil*_*bug 5

不知道任何开箱即用的Boost类型特性可以做到这一点,但同样可以使用模板专业化自己编写:

template<typename T>
struct member_pointer_class;

template<typename Class, typename Value>
struct member_pointer_class<Value Class::*>
{
    typedef Class type;
};

template<typename T>
struct member_pointer_value;

template<typename Class, typename Value>
struct member_pointer_value<Value Class::*>
{
    typedef Value type;
};

// TEST
#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>

struct Bar
{
    int var;
};

template <typename T>
void foo(T ptr)
{
    // test the code
    typedef typename member_pointer_class<T>::type ClassT;
    typedef typename member_pointer_value<T>::type ValueT;
    BOOST_STATIC_ASSERT_MSG((boost::is_same<ClassT, Bar>::value), "member_pointer_class is the same as Bar");
    BOOST_STATIC_ASSERT_MSG((boost::is_same<ValueT, int>::value), "member_pointer_value is the same as int");
}

int main()
{
    foo(&Bar::var);
}
Run Code Online (Sandbox Code Playgroud)

说明:

使用模板推导,我们提取成员指针的有趣类型--typedef member_pointer_class<T>::typemember_pointer_value<T>::type定义为适当的类型.typename在模板中消除歧义是必需的.该代码也可用于指向成员函数的指针.

如果类型不是指向成员的指针,则会member_pointer_class<T>::type给出编译器错误.