gpt4 book ai didi

c++ - 从指向成员变量的指针获取类和成员类型

转载 作者:太空狗 更新时间:2023-10-29 20:40:09 26 4
gpt4 key购买 nike

例如:

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);

在对 foo(...) 的最后一个函数调用中,ClassT 应该是 BarValueT应该是 int

我如何使用纯 C++(不能使用 C++11 功能)或 boost 来做到这一点?

最佳答案

不知道有任何开箱即用的 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);
}

解释:

使用模板推导,我们提取了成员指针的有趣类型 - typedef member_pointer_class<T>::typemember_pointer_value<T>::type被定义为适当的类型。 typename is required for disambiguation in templates.该代码还可以用于指向成员函数的指针。

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

关于c++ - 从指向成员变量的指针获取类和成员类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25228958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com