【问题标题】:template member variable specialization模板成员变量特化
【发布时间】:2016-01-30 19:58:27
【问题描述】:

我有一个 template 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% 的功能保持完全相同,我绝对不想为每一个专业化重新实现它们。我怎样才能做到这一点?

【问题讨论】:

    标签: c++ templates c++11 template-specialization


    【解决方案1】:

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

    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 上的代码示例,表明该想法至少在 C++11 标准下有效。

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

    【讨论】:

    • 非常有趣的方法,但我是否正确地假设我将无法像我的第一个示例那样直接访问工会成员?所以我将不得不使用 impl.x 和 impl.y ...?
    • 编辑以解决您对impl.x, impl.y等的担忧。
    • 谢谢 - 这正是我一直在寻找的!
    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多