模板成员变量特化

template member variable specialization

我有一个 template class 有很多功能,只想专门化其中的几个,同时还添加一个成员变量。

有没有可能不需要为专门的 class 重新实现所有功能?


我有:

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

    //a lot of functions

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

我想做的事情:

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

由于 95% 的功能保持完全相同,我绝对不想为每个专业化重新实现它们。我怎样才能做到这一点?

您可以做的一件事是制作一个辅助模板,该模板生成一个联合结构类型,该类型是您类型的 "core":

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() { ... }
};

然后您可以使用简单的继承来编写主要 class,例如:

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

请注意,这里没有进行虚拟调度。此外,您不必一定要继承 public,您可以将其设为私有并转发 Length 函数 publicly。

如果有用的话,您还可以更进一步,使用成熟的 CRTP。

这是 Coliru 上的代码示例,表明该想法至少适用于 C++11 标准。

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