2017-02-12 71 views
4

在我的課上,我們正在研究C++ 98所以我試圖找到正確的語法。C++模板類語法

應該怎麼寫聲明:

template <class T> 
class A{ 
public: 
    A(); 
    A(const A &rhs); 
    A &operator=(const A &rhs); 
}; 

還是應該是這樣的:

template <class T> 
class A{ 
public: 
    A(); 
    A(const A<T> &rhs); 
    A &operator=(const A<T> &rhs); 
}; 

我想實現是兩者的相同。

它們是不同的嗎?

+0

不是有你的課本上的例子? – Barmar

+0

@Barmar找不到這個特定的問題。 – Dannz

+1

我看到兩個語法正在使用http://stackoverflow.com/questions/7638296/how-to-write-template-class-copy-constructor和http://stackoverflow.com/questions/19167201/copy-constructor-的模板類 – Barmar

回答

8

鑑於

template <class T> class A { ... }; 

名稱A<T>A都是有效的名稱來指代A<T>在類的範圍。最喜歡使用更簡單的形式,A,但您可以使用A<T>

2

雖然[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.