2009-02-21 58 views
2

我想使用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或类似的设备是可能的。我在寻找的是有条件的数据成员。一如既往,您的帮助非常感谢。其他有效的建议也是受欢迎的。

谢谢。

+0

退房讨论:http://lists.boost.org/Archives/boost/2009/01 /147103.php – Anonymous 2009-02-21 19:36:49

回答

3

想到的一个解决方案是部分专用模板,这是马丁·约克发布的内容,但带有一些转折。

我会建议一个特殊的content_type-结构供应的布局类型,就像这样:

// 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)

+0

优秀。任何想法我应该如何访问那些不是公共分母(例如“pad”)的数据成员。一种方法是在数据成员不存在的情况下通过Boost.enable_if禁用其对应的访问器成员函数。感谢tabdamage。 – Ash 2009-02-21 10:55:43