当重载数组访问运算符时如何访问SIMD向量元素? [英] How to access SIMD vector elements when overloading array access operators?
问题描述
重载运算符
#ifdef _MSC_VER
float operator [](int idx)const {return v.m256_f32 [idx]; } // m256_f32 MSVC only
float& operator [](int idx){return v.m256_f32 [idx]; }
#else
float operator [](int idx)const {return v [idx]; }
float& operator [](int idx){return v [idx]; }
#endif
Clang的错误 p>
非const引用不能绑定到向量元素
float& operator [](int idx){return v [idx]; }
^ ~~~~
我认为你可能需要使用联合为此,例如:
union U {
__m256 v;
float a [8];
};
,则值运算符为:
float operator [](int idx)const {U u = {v}; return u.a [idx]; }
引用操作符很棘手,但我可以看到的唯一方法是通过类型惩罚,所以与通常的警告:
float& operator [](int idx){return((float *)& v)[idx]; }
我不确定这会编译,你可能需要 -fno-strict-aliasing
。
为了避免这种尴尬,我想你可以考虑改变你的成员变量 __ m256 v;
到 U u;
。
我只是希望你不在这种东西在任何性能关键循环内。
I am trying to make some SIMD code that works on MSVC compile with Clang on Xcode 6. Unfortunately I get an error where the array access operators have been overloaded in a custom vector class that I am unable to fix. The vector template has specializations for arrays of length 4 and 8 which use SIMD intrinsics, but the array access operator to return a reference to an element of the vector (for updating that element) gives me an error on clang "non-const reference cannot bind to vector element".
The overloaded operators:
#ifdef _MSC_VER
float operator[](int idx) const { return v.m256_f32[idx]; } // m256_f32 MSVC only
float& operator[](int idx) { return v.m256_f32[idx]; }
#else
float operator[](int idx) const { return v[idx]; }
float& operator[](int idx) { return v[idx]; }
#endif
The error from Clang:
non-const reference cannot bind to vector element
float& operator[](int idx) { return v[idx]; }
^~~~~~
I think you'll probably need to use a union for this, e.g.:
union U {
__m256 v;
float a[8];
};
and the value operator would then be:
float operator[](int idx) const { U u = { v }; return u.a[idx]; }
The reference operator is trickier though, and the only way I can see to do it is via type punning, so with the usual caveats:
float& operator[](int idx) { return ((float *)&v)[idx]; }
I'm not even sure this will compile, and you may need -fno-strict-aliasing
.
To avoid this nastiness I suppose you could consider changing you member variable from __m256 v;
to U u;
.
I just hope you're not doing this kind of thing inside any performance-critical loops.
这篇关于当重载数组访问运算符时如何访问SIMD向量元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!