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.如果有人可以建議更好的標題,那麼我會改變它,謝謝!
如果我理解正確的問題,你說的是[模板模板參數(http://stackoverflow.com/問題/ 213761 /什麼 - 是 - 某些用途-的模板,模板參數,在-C)。 –
爲什麼你認爲'std :: vector v1(1,123.0f);'應該調用構造函數3而不是構造函數2? –
如果3作品,然後我會刪除2,抱歉沒有明確表示。 –