2016-09-30 30 views
0

考慮以下幾點:公共接入

template<int T> 
class Test { 
public: 
    constexpr static int A = T; 
}; 

int main(int argsc, char** args) { 
    std::cout << Test<2>::T << std::endl; // Option 1 
    std::cout << Test<2>::A << std::endl; // Option 2 
} 

爲什麼不選擇1個編譯?看來static constexpr A只是一個額外的步驟。 T是否不公開?

有沒有比上面創建可公開訪問的成員A更清潔的方式獲得T

+0

您不能在類之外訪問模板參數。 – plasmacel

+0

@plasmacel - 爲什麼這是真的?創建'A'的步驟似乎沒有必要。 – Jack

+1

您也可以創建一個允許檢索模板參數的特徵。 'template TestTrait;模板 TestTrait > struct {constexpr static int value = N; };' – Jarod42

回答

2

爲什麼不選擇1編譯?

因爲模板參數只是參數的名稱。您可以重命名它們,即:

template <class T> struct X; 

// refers to same X 
template <class U> struct X { ... }; 

// still the same X 
template <class V> 
void X<V>::foo() { ... }; 

出於同樣的原因,您可以在聲明和定義之間對函數參數進行不同的命名。要求模板參數的名稱在類模板中自動可見將意味着它必須在第一時間修復。

有沒有比在上面創建一個可公開訪問的成員更清晰的方式來獲取T?

創建可公開訪問的成員通常是要走的路。或者,您可以創建一個外部特徵:

template <class T> struct X { using type = T; }; // internal 

template <class > struct get_type; 
template <class T> struct get_type<X<T>> { using type = T; }; // external 
+0

如果'type'不是一個類型,而是一個'int'值,'use type = T'工作嗎? – Jack

+0

@Jack不,你必須有'static constexpr int value = T;'我只是使用類型,因爲類型更典型。 – Barry

+0

需要提及的是,您可以在類之外重命名參數的功能不排除通過其原始名稱訪問參數的功能,或者通過索引提取參數。所以它更像是標準的限制。 – plasmacel