【问题标题】:C++ template class syntaxC++ 模板类语法
【发布时间】:2017-02-12 05:47:22
【问题描述】:

在我的课堂上,我们正在学习 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);
};

我猜他们两个的实现是一样的。

它们之间有区别吗?

【问题讨论】:

标签: c++ templates c++98


【解决方案1】:

给定

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

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

【讨论】:

    【解决方案2】:

    虽然 R Sahu 的回答是正确的,但我认为最好说明AA&lt;T&gt; 不同的情况,特别是在实例化模板参数超过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.

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 2016-08-23
      • 2012-12-04
      相关资源
      最近更新 更多