我想使用 SIMD 指令和编译器内在函数来优化我的 Vector 和 Matrix 类(准确地说是类模板)。我只想针对元素类型为“float”的情况进行优化。使用 SIMD 指令需要接触数据成员。由于我不想被维护两个单独的类的麻烦所困扰,因此我希望能够根据模板参数的类型启用/禁用某些数据成员。这种方法的另一个优点(如果适用的话)是,我可以将一般情况下的相同代码用于我不想为其编写专门化的函数。因此,我想用伪代码实现的是:
template< typename T >
class Vector3 {
if type( T ) == float:
union {
__m128 m128;
struct {
float x, y, z, pad;
};
};
else
T x, y, z;
endif
};
Run Code Online (Sandbox Code Playgroud)
我知道通过使用 Boost.enable_if 或类似的工具可以有条件地包含成员函数。不过,我正在寻找的是有条件地包含数据成员。一如既往,非常感谢您的帮助。也欢迎其他有效的建议。
谢谢。
我想到的一个解决方案是部分专门化的模板,这是 Martin York 发布的内容,但有所不同。
我建议使用特殊的 content_type-struct 来提供布局类型,如下所示:
// content for non float types
template<typename T>
struct content_type {
typedef typename T member_type;
member_type x,y,z;
member_type& X { return x; }
// ...
// if access to optional members is needed, better use CT_ASSERT or similar
member_type& Pad { char assert_error_no_pad_here[0]; }
};
// content for float types
struct content_type<float> {
typedef typename float member_type;
member_type x, y, z, pad;
member_type& X { return x; }
// ...
member_type& Pad { return pad; }
};
template<typename T>
class Vector3 {
typedef typename content_type<T> layout_type;
typedef typename content_type<T>::member_type member_type;
layout_type _content;
public:
member_type& X { return _content.X(); }
memmber_type& Pad { return _content.Pad(); }
};
// or maybe, if memory layout is not important, just inherit (watch for virtual members)
template<typename T>
class Vector3 : public content_type<T> {
typedef typename content_type<T> layout_type;
typedef typename content_type<T>::member_type member_type;
};
Run Code Online (Sandbox Code Playgroud)
优点是您只需编写一次 Vector3 及其所有逻辑。
不过,您需要一个较新的编译器才能正确执行此操作(MSVC>7,gcc>3)
| 归档时间: |
|
| 查看次数: |
2549 次 |
| 最近记录: |