雖然[R薩胡的答案是正確的,我認爲這是很好的說明,其中A
不如A<T>
一樣,特別是在有超過1個實例化模板參數的情況。
例如,當爲具有兩個模板參數的模板化類編寫複製構造函數時,因爲參數的順序很重要,所以您需要明確寫出重載的模板化類型。
下面是一個例子與 「鍵/值」 類型的類:
#include <iostream>
// Has overloads for same class, different template order
template <class Key, class Value>
struct KV_Pair {
Key key;
Value value;
// Correct order
KV_Pair(Key key, Value value) :
key(key),
value(value) {}
// Automatically correcting to correct order
KV_Pair(Value value, Key key) :
key(key),
value(value) {}
// Copy constructor from class with right template order
KV_Pair(KV_Pair<Value, Key>& vk_pair) :
key(vk_pair.value),
value(vk_pair.key) {}
// Copy constructor from class with "wrong" template order
KV_Pair(KV_Pair<Key, Value>& vk_pair) :
key(vk_pair.key),
value(vk_pair.value) {}
};
template <class Key, class Value>
std::ostream& operator<<(std::ostream& lhs, KV_Pair<Key, Value>& rhs) {
lhs << rhs.key << ' ' << rhs.value;
return lhs;
}
int main() {
// Original order
KV_Pair<int, double> kv_pair(1, 3.14);
std::cout << kv_pair << std::endl;
// Automatically type matches for the reversed order
KV_Pair<double, int> reversed_order_pair(kv_pair);
std::cout << reversed_order_pair << std::endl;
}
See it live on Coliru.
不是有你的課本上的例子? – Barmar
@Barmar找不到這個特定的問題。 – Dannz
我看到兩個語法正在使用http://stackoverflow.com/questions/7638296/how-to-write-template-class-copy-constructor和http://stackoverflow.com/questions/19167201/copy-constructor-的模板類 – Barmar