[英]Boost Fusion Types offsetof
我目前正在嘗試計算一個增強融合適應結構中數據成員的偏移量,但我不確定是否有一種優雅的方法可以做到這一點。 我想做類似以下的事情:
#include <iostream>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/sequence/intrinsic/at.hpp>
#include <boost/fusion/include/at.hpp>
#include <cstddef.h>
struct test {
int a;
char c;
double b;
};
BOOST_FUSION_ADAPT_STRUCT(
test,
(int, a)
(char, c)
(double, b)
)
int main() {
test s{1, 2, 3.0};
// The following code doesn't work... I'm just trying to get my point across
std::cout << "offset is :" << offsetof(test, at<1>(s)) << std::endl;
}
關鍵是我不想在offsetof函數中明確聲明'a'或'b'或'c'。 這本身並沒有那么有用,但是我想在boost for_each循環中使用它,這樣我就可以在編譯時計算任何結構的所有數據成員的偏移量。
如果您有任何想法,我很樂意聽到他們!
我不是專家,但我認為由於offsetof
的性質,沒有辦法實現你想要的東西而不需要使用宏。 以下示例僅使用宏為結構的每個成員創建一個特征,每當您訪問它時返回其預先計算的偏移量。
#include <iostream>
#include <string>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/mpl.hpp>
#include <boost/mpl/range_c.hpp>
#include <cstddef>
namespace not_fusion
{
template <typename StructName, int N>
struct offset_of;
}
//Actually creates each respective 'offset_of' trait
//you could change 'BOOST_STATIC_CONSTANT(std::size_t,...)'
//with a 'static constexpr std::size_t ...' or whatever you like
#define CREATE_OFFSET_TRAIT(R,STRUCT_NAME,INDEX,MEMBER) \
template <> struct offset_of<STRUCT_NAME, INDEX>{ BOOST_STATIC_CONSTANT(std::size_t, value = offsetof(STRUCT_NAME,MEMBER)); };
//Iterates the struct members in order to create the corresponding 'offset_of' traits
#define NOT_FUSION_SAVE_OFFSETS(STRUCT_NAME,MEMBERS) \
namespace not_fusion { \
BOOST_PP_SEQ_FOR_EACH_I(CREATE_OFFSET_TRAIT,STRUCT_NAME,MEMBERS) \
}
//Simply "invokes" 'BOOST_FUSION_ADAPT_STRUCT' and 'NOT_FUSION_SAVE_OFFSETS'
#define ADAPT_STRUCT_AND_SAVE_OFFSETS(TYPE,...) \
BOOST_FUSION_ADAPT_STRUCT(TYPE,__VA_ARGS__) \
NOT_FUSION_SAVE_OFFSETS(TYPE,BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))
struct test1 {
int a;
char c;
double b;
};
struct test2 {
char c;
short s;
int i;
};
ADAPT_STRUCT_AND_SAVE_OFFSETS(test1,a,c,b);
ADAPT_STRUCT_AND_SAVE_OFFSETS(test2,c,s,i);
template <typename Struct>
void print_offsets(const std::string& name,const Struct&)
{
//This could be changed to use 'std::integer_sequence' instead of mpl
std::cout << "Offsets for " << name << ":" << std::endl;
typedef boost::mpl::range_c<unsigned, 0, boost::fusion::result_of::size<Struct>::value > Indices;
boost::fusion::for_each(Indices(),
[](auto index)
{
std::cout << boost::fusion::extension::struct_member_name<Struct,index>::call() << " -> " << not_fusion::offset_of<Struct,index>::value << std::endl;
}
);
}
int main() {
test1 t1{1, 2, 3.0};
test2 t2{1,2,3};
print_offsets("test1",t1);
print_offsets("test2",t2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.