Conditional inclusion / exclusion of data elements inside class templates

I want to optimize the Vector and Matrix classes (which are exact class templates) using SIMD instructions and compiler built-in functions. I just want to optimize for the case when the element type is "float". Using SIMD commands requires touching data items. Since I don’t want to worry about saving two separate classes, I want to be able to enable / disable some data elements depending on the type of template parameter. Another advantage of this approach, if applicable, is that I can use the same code from the general case for functions for which I do not want to write specialization. Therefore, what I want to achieve in pseudocode:

template< typename T > class Vector3 { if type( T ) == float: union { __m128 m128; struct { float x, y, z, pad; }; }; else T x, y, z; endif }; 

I know that conditional inclusion of member functions is possible using Boost.enable_if or similar objects. However, I am looking for conditional inclusion of data. As always, your help is greatly appreciated. Other helpful suggestions are also welcome.

Thanks.

+2
source share
1 answer

One solution that comes to mind is the partially specialized templates that Martin York published, but with a twist.

I would recommend a special content_type-struct to feed the layout type, for example:

 // 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; }; 

The advantage is that you only need to write Vector3 with all its logic once.

You need a moderately recent compiler to do this correctly (MSVC> 7, gcc> 3)

+4
source

Source: https://habr.com/ru/post/1246143/


All Articles