2014-12-01 40 views
2

下面的例子應該說明我的問題:如果我有一個類爲模板參數,我怎麼可以使用類的(常量)的屬性...如何使用類的屬性作爲模板參數/專業化?

  1. 直接,通過標記行給出與(1)。據我所知, 這應該工作。這是「正確」的方式嗎?

  2. 作爲模板專門化的參數。所以我想專門化一個固定容器,一個不固定。在這裏,我不知道。

代碼示例:

class IdxTypeA{ 
    const bool fixed = true; 
    const int LEN = 5; // len is fixed on compile time 
} 

class IdxTypeB{ 
    const bool fixed = false; 
    int len; // len can be set on runtime 
} 

class IdxTypeC{ 
    const bool fixed = false; 
    int len; // len can be set on runtime 
} 

template<class IDX> class Container { } 

template<> 
class Container<here comes the specialisation for fixed len>{ 
    int values[IDX.LEN]; // **** (1) ***** 
} 

template<> 
class Container<here comes the specialisation for not fixed length>{ 
    ... 
} 

(現在的問題是不是容器,這只是粗略的例子。)

回答

1

首先,你需要打開編譯時屬性爲實際的常數通過使他們的表達式static

class IdxTypeA { 
    static const bool fixed = true; 
    static const int LEN = 5; // len is fixed on compile time 
} 

有了這個,你可以(部分),專門對這些就好了,像這樣somethig:

template<class IDX, bool IS_FIXED = IDX::fixed> class Container; 

template <class IDX> 
class Container<IDX, true> 
{ 
    int values[IDX::LEN]; 
}; 

template <class IDX> 
class Container<IDX, false> 
{ 
}; 
+0

我澄清的問題了一下:這可能是我也有IdxTypeC,IdxTypeD等可固定或不固定的。他們都應該引發正確的專業化。所以我不想專注於某種類型,而是針對某種特性。 – Michael 2014-12-01 19:22:51