2016-02-15 29 views
7

テンプレートクラスでは、条件付きでテンプレートにプロパティエイリアスを定義する方法はありますか?テンプレートクラスの条件付き参照宣言

例:

template<class Type, unsigned int Dimensions> 
class SpaceVector 
{ 
public: 
    std::array<Type, Dimensions> value; 
    Type &x = value[0]; // only if Dimensions >0 
    Type &y = value[1]; // only if Dimensions >1 
    Type &z = value[2]; // only if Dimensions >2 
}; 

はこの条件宣言は可能ですか?はいの場合、どうですか?

答えて

7

最初の2例を特化:

template<class Type> 
class SpaceVector<Type, 1> 
{ 
public: 
    std::array<Type, 1> value; // Perhaps no need for the array 
    Type &x = value[0]; 
}; 

template<class Type> 
class SpaceVector<Type, 2> 
{ 
public: 
    std::array<Type, 2> value; 
    Type &x = value[0]; 
    Type &y = value[1]; 
}; 

あなたが共通の基底クラスを持っているなら、あなたは一般的な機能のための多型の測定量を得ることができます。

+0

「Dimensions」が有効であることを保証するために、プライマリテンプレートに 'static_assert'も必要です。 – TartanLlama

+0

しかし、なぜスペシャライゼーションはお互いから派生していないのですか? –

+0

@songyuanyao:それを変更しましたが、私はMSVC2013でコンパイルした(おそらくは間違っていました)。 – Bathsheba

2

あなたは、配列なしで行うことができる場合、あなたはこれを行うことができます:

template<class Type, std::size_t Dimension> 
class SpaceVector 
{ 
public: 
    Type x; 
}; 

template<class Type> 
class SpaceVector<Type, 2> : public SpaceVector<Type,1> 
{ 
public: 
    Type y; 
}; 

template<class Type> 
class SpaceVector<Type, 3> : public SpaceVector<Type,2> 
{ 
public: 
    Type z; 
}; 

をあなたは以上の三つの要素をサポートすることを決定した場合、これは、よりスケーラブルですが、それ以外は、バテシバの答えは、おそらくより適しています。

関連する問題