2009-02-21 41 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

相關問題