簡體   English   中英

模板成員變量專門化

[英]template member variable specialization

我有一個包含許多函數的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%的功能保持完全相同 ,我絕對不希望為每一個專業化重新實現它們。 我怎樣才能做到這一點?

你可以做的一件事是創建一個幫助器模板,生成一個結構與聯合類型,它是你的類型的“核心”:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM