繁体   English   中英

C ++模板类语法

[英]C++ template class syntax

在我的课堂上,我们正在研究C ++ 98,所以我试图找到合适的语法。

如何写出声明:

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);
};

我想两者的实现是一样的。

它们彼此不同吗?

特定

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

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

虽然R Sahu的答案是正确的,但我认为说明AA<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;
}

在Coliru上看到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM