[英]C++ template class syntax
In my class, we are studying C++98 so I'm trying to find the proper syntax. 在我的课堂上,我们正在研究C ++ 98,所以我试图找到合适的语法。
How should one write the declaration: 如何写出声明:
template <class T>
class A{
public:
A();
A(const A &rhs);
A &operator=(const A &rhs);
};
Or should it be like this: 或者应该是这样的:
template <class T>
class A{
public:
A();
A(const A<T> &rhs);
A &operator=(const A<T> &rhs);
};
I guess the implementation is the same for both of them. 我想两者的实现是一样的。
Are they different from one to another? 它们彼此不同吗?
Given 特定
template <class T> class A { ... };
The names A<T>
and A
are both valid names to refer to A<T>
in the scope of the class. 名称
A<T>
和A
都是有效的名称,用于引用类范围内的A<T>
。 Most prefer to use the simpler form, A
, but you may use A<T>
. 大多数人更喜欢使用更简单的形式
A
,但你可以使用A<T>
。
While R Sahu 's answer is correct, I think it's good to illustrate the case where A
is not the same as A<T>
, particularly where there are more than 1 instantiated template argument. 虽然R Sahu的答案是正确的,但我认为说明
A
与A<T>
不同的情况是好的,特别是在有超过1个实例化模板参数的情况下。
For example, when writing a copy constructor for a templated class with two template arguments, because the order of the arguments matters, you need to explicitly write out the templated types for the overloads. 例如,在为带有两个模板参数的模板化类编写复制构造函数时,由于参数的顺序很重要,因此需要显式写出重载的模板化类型。
Here is an example with a "Key/Value" type class: 以下是“键/值”类型类的示例:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.