gpt4 book ai didi

c++ - 在类模板中有条件地包含/排除数据成员

转载 作者:搜寻专家 更新时间:2023-10-31 01:23:52 24 4
gpt4 key购买 nike

我想使用 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
};

我知道通过使用 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;
};

优点是您只需编写 Vector3 及其所有逻辑一次。

虽然 (MSVC>7, gcc>3),但您需要适度更新的编译器才能正确执行此操作

关于c++ - 在类模板中有条件地包含/排除数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/572684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com