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

时间:2016-11-28 18:29:26

标签: c++

我的代码使用着名的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) );})

1 个答案:

答案 0 :(得分:3)

为自己定制解决方案。没有模板会更好:

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