C++中的"container_of"宏,具有与 C 相同的签名

`container_of` macro in C++ with the same signature as C's

本文关键字:container 中的 of C++      更新时间:2023-10-16

我有使用著名的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 中,我们通常使用typeofcontainer_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