当重载数组访问运算符时如何访问SIMD向量元素? [英] How to access SIMD vector elements when overloading array access operators?

查看:152
本文介绍了当重载数组访问运算符时如何访问SIMD向量元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一些SIMD代码工作在MSVC编译与Clang在Xcode 6.不幸的是,我遇到一个错误,数组访问操作符已经重载在自定义向量类,我无法修复。向量模板具有使用SIMD内在函数的长度为4和8的数组的特殊化,但数组访问运算符返回向量的一个元素的引用(用于更新该元素)给我一个clang上的错误非const引用不能绑定到向量元素。



完整的源代码



重载运算符

  #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".

Full source code

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆