【问题标题】:Conditional Inclusion/Exclusion of Data Members Inside Class Templates类模板内数据成员的条件包含/排除
【发布时间】:2009-02-21 09:31:36
【问题描述】:

我想使用 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 或类似工具可以有条件地包含成员函数。不过,我正在寻找的是有条件地包含数据成员。与往常一样,非常感谢您的帮助。也欢迎其他有效的建议。

谢谢。

【问题讨论】:

标签: c++ templates


【解决方案1】:

想到的一个解决方案是部分专业化的模板,这是 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)

【讨论】:

  • 优秀。知道我应该如何访问那些不属于公分母的数据成员(例如“pad”)。一种方法是通过 Boost.enable_if 禁用它们相应的访问器成员函数,以防这些数据成员不存在。谢谢tabdamage。
  • 我为此添加了一个解决方案,但也许 boost::enable_if 更简洁一些。最好的解决方案取决于你的实际使用,为了让运行时逻辑尽可能干净,类型定义需要稍微复杂一些。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2011-08-05
  • 2022-11-22
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多