模板成员变量专门化

bri*_*ore 5 c++ templates template-specialization c++11

我有template class很多函数,只想特化其中的一些,同时还添加了一个成员变量.

这是否可能无需重新实现专业类的所有功能?


是)我有的:

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

    //a lot of functions

    T Length() { ... };
};
Run Code Online (Sandbox Code Playgroud)

我想做的事:

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>
    };
};
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*eck 5

您可以做的一件事是制作一个辅助模板,该模板生成一个具有联合结构的类型,该类型是您类型的“核心”:

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

  T length() { ... }
};
Run Code Online (Sandbox Code Playgroud)

float根据需要专门用于:

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

  float Length() { ... }
};
Run Code Online (Sandbox Code Playgroud)

然后你可以使用简单的继承来编写主类,例如:

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...
};
Run Code Online (Sandbox Code Playgroud)

请注意,这里没有进行虚拟调度。此外,您不一定需要公开继承,您可以将其设为私有并Length公开转发该功能。

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

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

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