2014-06-19 22 views
1
class trytemplate 
{ 
public: 
    //////// 1 
    template <typename T> 
    trytemplate(const T& p) 
    { 
     std::cout << p << std::endl; 
    } 

    //////// 2 
    template <typename U> 
    trytemplate(const std::vector<U>& p) 
    { 
     std::cout << p[0] << " " << p.size() << std::endl; 
    } 

    //////// 3 
    template <typename U, typename V> 
    trytemplate(const V<U>& p) 
    { 
     std::cout << p[0] << " " << p.size() << std::endl; 
    } 
}; 

ctor 2工作正常,但我想使它像3(3不編譯)。
所以,我可以這樣做:是否可以指定模板類的一部分? (在'<'和'< >'之前的部分)

int i = 123; 
trytemplate o1(i); // call ctor 1 

std::vector<float> v1(1, 123.0f); 
trytemplate o2(v1); // ideally can be deduced by compiler, and call ctor 3 

MyVector<float> v2(1, 123.0f); 
trytemplate o3(v2); // ideally can be deduced by compiler, and call ctor 3 

在這種情況下,我可以通過任何載體狀容器,只要確保類有operator[]size()

所以問題是:是否有可能讓ctor變成3號?
或者有沒有更好的方法?

P.S.如果有人可以建議更好的標題,那麼我會改變它,謝謝!

+2

如果我理解正確的問題,你說的是[模板模板參數(http://stackoverflow.com/問題/ 213761 /什麼 - 是 - 某些用途-的模板,模板參數,在-C)。 –

+0

爲什麼你認爲'std :: vector v1(1,123.0f);'應該調用構造函數3而不是構造函數2? –

+0

如果3作品,然後我會刪除2,抱歉沒有明確表示。 –

回答

4

使用模板模板參數

template <template<typename> class V, typename U> 
trytemplate(const V<U>& p) 
{ 
    std::cout << p[0] << " " << p.size() << std::endl; 
} 

您還可以添加可變參數模板接受需要超過一個模板參數的類模板。

template <template<typename...> class V, typename... Params> 
trytemplate(const V<Params...>& p) 
{ 
    std::cout << p[0] << " " << p.size() << std::endl; 
} 

請注意,如果您使用非可變參數(第一)版本,那麼你通過在類模板應該只需要一個模板參數。這意味着它不能與std::vector一起使用,因爲它需要第二個模板參數,分配器類型(其默認參數爲std::allocator<T>)。如果你的編譯器不支持可變參數模板,像VS2012無月CTP,然後用這個

template <template<typename, typename> class V, typename U, typename A> 
trytemplate(const V<U, A>& p) 
{ 
    std::cout << p[0] << " " << p.size() << std::endl; 
} 
+0

嗨,我想模板模板參數,但它給我編譯錯誤,很奇怪。 –

+0

錯誤C2039:'size':不是'std :: _ Vector_val <_Val_types>'的成員並且錯誤C2676:binary'[':'const std :: _ Vector_val <_Val_types>'未定義此運算符或轉換爲可接受的類型預定義的運算符 –

+0

如果我評論ctor1並且只嘗試實例化'trytemplate o2(v1)',我得到了上述錯誤。如果我同時保留ctor1和ctor3,則會發生另一個錯誤:錯誤C2679:二進制'<<':找不到操作符,該操作符需要'const std :: vector <_Ty>'類型的右側操作數(或者沒有可接受的轉換) 。似乎編譯器正在嘗試使用ctor1而不是ctor3。 –

相關問題