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

编程入门 行业动态 更新时间:2024-10-27 08:31:23
本文介绍了从指向成员变量的指针获取类和成员类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如:

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应该是Bar,而ValueT应该是int.

Inside the last function call to foo(...), ClassT should be Bar and ValueT should be int.

我该如何使用普通C ++(不能使用C ++ 11功能)或增强功能?

How can I do this with plain C++ (can't use C++11 features), or boost?

推荐答案

不知道要使用任何现成的Boost类型特征,但是您可以使用模板专门化来编写相同的内容:

Not aware of any out-of-the-box Boost type trait to do this, but the same can be written by yourself using template specialization:

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

说明:

使用模板推论,我们提取成员指针的有趣类型-将typedefs member_pointer_class<T>::type和member_pointer_value<T>::type定义为适当的类型.需要 typename模板中的歧义.该代码还可用于指向成员函数的指针.

Using template deduction we extract the interesting types of the member pointer - the typedefs member_pointer_class<T>::type and member_pointer_value<T>::type are defined to the appropriate types. typename is required for disambiguation in templates. The code can be also used for pointer to member functions.

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

If the type is not a pointer to member, the member_pointer_class<T>::type gives a compiler error.

更多推荐

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

本文发布于:2023-07-28 02:46:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226582.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成员   指针   变量   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!