Specialization of template variables

I have template classmany functions and I just want to highlight some of them and also add a member variable.

Is it possible without having to redefine all functions for a specialized class?


What I have:

template<class T> class Vector3
{
    union {
        T data[3];
        struct { T x, y, z; };
    };

    //a lot of functions

    T Length() { ... };
};

What I want to do:

template<> class Vector3<float>
{
    union {
        float data[3];
        struct { float x, y, z; };

        //new union member only for <float>!
        __m128 xmm;
    };

    float Length() {
        //special instructions for special case <float>
    };
};

Since 95% of all functions remain exactly the same, I definitely do not want to redefine them for each individual specialization. How can i achieve this?

+4
source share
1 answer

One thing you can do is create an auxiliary template that generates a structure type with a union, which is the "core" of your type:

template <typename T>
struct Vector3_core {
  union {
    T data[3];
    struct { T x, y, z; };
  };

  T length() { ... }
};

float :

template <>
struct Vector3_core<float> {
  union {
    float data[3];
    struct { float x, y, z; };
    __m128 xmm;
  };

  float Length() { ... }
};

:

template<class T> class Vector3 : public Vector3_core<T>
{
  // Need to pull anonymous-struct members into this class' scope
  using Vector3_core<T>::x;
  using Vector3_core<T>::y;
  using Vector3_core<T>::z;

  // All your functions...
};

, . , , Length .

CRTP, .

Coliru, , ++ 11, .

http://coliru.stacked-crooked.com/a/ef10d0c574a5a040

+1

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


All Articles