C++中的"container_of"宏,具有与 C 相同的签名
`container_of` macro in C++ with the same signature as C's
我有使用著名的container_of
宏来实现仅宏链表库的代码。
它在 C 语言中完美运行。现在我想支持C++,所以我需要一个container_of
替换与以下签名匹配的C++:
container_of(ptr, type, member)
C 实现是这样的:
#define container_of(ptr, type, member) ({
const typeof( ((type *)0)->member ) *__mptr = (ptr);
(type *)( (char *)__mptr - offsetof(type,member) );})
为自己量身定制了一个解决方案。没有模板会更好:
template<class P, class M>
size_t my_offsetof(const M P::*member)
{
return (size_t) &( reinterpret_cast<P*>(0)->*member);
}
template<class P, class M>
P* my_container_of_impl(M* ptr, const M P::*member)
{
return (P*)( (char*)ptr - my_offsetof(member));
}
#define my_container_of(ptr, type, member)
my_container_of_impl (ptr, &type::member)
因为在 C 中,我们通常使用typeof
和container_of
来获取变量的类型,例如:
typedef struct _AStruct
{
int data_field;
} AStruct;
AStruct as;
int * ptr = &as.data_field;
my_container_of(ptr, AStruct, data_field);
my_container_of(ptr, typeof(as), data_field);
我们也可以提供一个额外的宏来实现typeof
等价:
#include <type_traits>
#define my_typeof(___zarg) std::remove_reference<decltype(___zarg)>::type
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- vector.resize()中的分配错误
- 使用指针从C++中的数组中获取最大值
- arr[-1]在c++中的奇怪行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 将值指定给向量(2D)的向量中的某个位置
- 从存储在 std::container 中的结构中提取元素