Switching back and forth between Array of Structures (AoS) and Structure of Arrays (SoA)

倾然丶 夕夏残阳落幕 提交于 2019-12-04 03:42:17

I'm going to choose this syntax: cs.foo[42] to be the single syntax and use typedefs to switch between arrangements:

So, obviously given C_SoA from your post, the above syntax works and we can have:

typedef C_SoA Arrangement;

Arrangement cs;

In order to use std::vector<C_AoS> instead we are going to have to introduce something else:

typedef std::vector<C_AoS> AOS;

template<class A, class C, class T>
struct Accessor {
    T operator[](size_t index){
            return arr[index].*pMember;
    }
    T (C::*pMember);
    A& arr;
    Accessor(A& a, T (C::*p)): arr(a), pMember(p){}
};

struct Alt_C_AoS{
    Accessor<AOS, C_AoS, int> foo;
    Accessor<AOS, C_AoS, double> bar;

    AOS aos;
    Alt_C_AoS():foo(aos, &C_AoS::foo), bar(aos, &C_AoS::bar){}
};

Now we can have:

//Choose just one arrangement
typedef Alt_C_AoS Arrangement;
//typedef C_SoA Arrangement;

Arrangement cs;
...
std::cout << cs.foo[42] << std::endl;

Essentially this converts container dot member index into container index dot member.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!