C++ C++;模板类语法

C++ C++;模板类语法,c++,templates,c++98,C++,Templates,C++98,在我的课堂上,我们正在学习C++98,所以我试图找到正确的语法 如何撰写声明: template <class T> class A{ public: A(); A(const A &rhs); A &operator=(const A &rhs); }; 模板 甲级{ 公众: A(); A(施工A和rhs); A和运算符=(常数A和rhs); }; 或者应该是这样的: template <class T> class

在我的课堂上,我们正在学习C++98,所以我试图找到正确的语法

如何撰写声明:

template <class T>
class A{
public:
    A();
    A(const A &rhs);
    A &operator=(const A &rhs);
};
模板
甲级{
公众:
A();
A(施工A和rhs);
A和运算符=(常数A和rhs);
};
或者应该是这样的:

template <class T>
class A{
public:
    A();
    A(const A<T> &rhs);
    A &operator=(const A<T> &rhs);
};
模板
甲级{
公众:
A();
A(施工A和rhs);
A和运算符=(常数A和rhs);
};
我想这两种方法的实现是一样的

它们彼此不同吗?

给定

template <class T> class A { ... };
模板类A{…};

名称
A
A
都是类范围内引用
A
的有效名称。大多数人更喜欢使用更简单的形式,
A
,但您可以使用
A

虽然R Sahu的答案是正确的,但我认为最好说明
A
A
不同的情况,特别是在有多个实例化模板参数的情况下

例如,当为具有两个模板参数的模板化类编写副本构造函数时,由于参数的顺序很重要,因此需要显式写出重载的模板化类型

下面是一个“键/值”类型类的示例:

#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;
}
#包括
//具有相同类、不同模板顺序的重载
模板
结构千伏对{
钥匙;
价值观;
//正确顺序
KV_对(键、值):
钥匙(钥匙),,
值(值){}
//自动更正为正确的顺序
KV_对(值、键):
钥匙(钥匙),,
值(值){}
//使用正确的模板顺序从类复制构造函数
KV_线对(KV_线对和vk_线对):
密钥(vk_对值),
值(vk_pair.key){}
//使用“错误”的模板顺序从类复制构造函数
KV_线对(KV_线对和vk_线对):
密钥(vk_对密钥),
值(vk_pair.value){}
};
模板

std::ostream&operator你的教科书中没有例子吗?@Barmar找不到关于这个特定问题的例子。我看到和中都使用了语法