【发布时间】:2015-06-10 11:26:52
【问题描述】:
我使用 Clang SIMD 向量扩展编写了一个向量类型。它工作得很好,除非我需要检查两个向量是否相等。 == 运算符似乎没有为 Clang 的向量类型正确定义。尝试将两个向量与== 进行比较奇怪地似乎评估为与被比较的两个向量相同类型的第三个向量,而不是bool。我觉得这很奇怪,因为应用 + 或 - 等其他操作可以毫无问题地编译,并输出预期的结果。这是我的代码,使用 Clang 3.5 (Xcode) 编译:
// in vect.h
template <typename NumericType>
using vec2 = NumericType __attribute__((ext_vector_type(2))) ;
//in main.cpp
#include "vect.h"
int main(int argc, const char ** argv) {
vec2<int> v0 {0, 1} ;
vec2<int> v1 {0, 1} ;
vec2<int> sumVs = v0 + v1 ; //OK: evaluates to {0, 2} when run
bool equal = (v0 == v1) ; /* Compiler error with message: "Cannot initialize
a variable of type 'bool' with an rvalue of type 'int __attribute__((ext_vector_type(2)))'" */
return 0;
}
有没有什么方法可以让operator == 与 Clang 的向量类型一起使用,或者有任何其他解决方法来解决这个问题?由于它们被认为是原始类型而不是类类型,因此我不能自己重载比较运算符,并且编写全局 equals() 函数似乎很笨拙和不雅。
更新:或者如果没有人有我正在寻找的解决方案,也许有人可以解释比较两个 SIMD 向量时== 运算符的默认行为?
更新 #2:Hurkyl 建议 == 对两个向量进行向量化比较。我更新了我的代码以测试这种可能性:
template <typename NumericType>
using vec3 = NumericType __attribute__((ext_vector_type(3))) ;
int main(int argc, const char ** argv) {
vec3<int> v0 {1, 2, 3} ;
vec3<int> v1 {3, 2, 1} ;
auto compareVs = (v0 == v1) ;
return 0;
}
LLDB 将 compareVs 的值报告为 {0, -1, 0},如果发生这种情况,这似乎几乎是正确的,但 true 会是 -1,false 会是 0 似乎很奇怪。
更新 #3:好的,多亏了我得到的反馈,我现在对如何将关系和比较运算符应用于向量有了更好的理解。但是我的基本问题仍然是一样的。我需要一种简单而优雅的方法来检查任何两个 SIMD 类型向量 v1 和 v2,它们是否等效。换句话说,我需要能够检查v1 和v2 中的每个索引i,v1[i] == v2[i],表示为单个布尔值(即,not bool 的向量/数组)。如果唯一的答案真的是这样的函数:
template <typename NumericType>
bool equals(vec2<NumericType> v1, vec2<NumericType> v2) ...
...那我就接受了。但我希望有人能提出一些不那么笨拙的建议。
【问题讨论】:
-
如果我不得不猜测,
operator==正在做一个 vectorized 比较,因此返回一个 vector 结果。 -
这是有道理的。我稍微修改了我的代码来测试这个假设,我会用结果更新我的问题。
-
在 C/C++ 中,当您将
int转换为bool时,您将得到false用于0和true用于其他任何内容,因此您在第二次更新中得到的结果是很好。