【问题标题】:friend function in template definition模板定义中的友元函数
【发布时间】:2010-01-16 09:39:40
【问题描述】:

我的问题与this one 有点相关。

我想为某个类重载运算符

template <class T>
class A{
  T t;
public:
  A(T init) : t(init){}
  friend ostream& operator<< <> (ostream &os, const A<T> &a); //need forward declaration
  //template <class U> friend ostream& operator<< (ostream &os, const A<U> &a);
};

我是否用不同的符号来定义相同的事物?还是第一个版本在

【问题讨论】:

    标签: c++ templates friend-function


    【解决方案1】:

    第一个版本将友谊限制为特定类型 A&lt;T&gt;operator&lt;&lt;,而第二个版本将任何带有 A&lt;SomeType&gt;operator&lt;&lt; 设为朋友。

    所以是的,第一个限制性更强:

    template<class T>
    ostream& operator<< (ostream& os, const A<T>& a) {
        A<double> b(0.0);
        b.t; // compile error with version 1, fine with version 2
        return os;
    }
    
    int main() {
        A<int> a(0);
        cout << a << endl;
    }
    

    【讨论】:

    • 几件事。首先,我认为您的意思是 'os
    • 我的头似乎在其他地方 - 但同时修复了它。
    【解决方案2】:

    碰巧友元函数的定义对模板有一个例外。它允许你这样写:

    template <class T>
    class A{
      T t;
    public:
      A(T init) : t(init){}
      friend ostream& operator<<(ostream &os, const A &a)
      {  // Implementation in the class
      }
    };
    

    它的优点是为您创建的每个A&lt;T&gt; 实例自动创建一个普通函数。

    供参考:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16

    【讨论】:

    • 你的意思是“例外”,你不必在运算符的定义中写 A ?我的问题:这真的是优势吗?好的,您没有
    • 主要优点是您不需要前向声明......但是您必须始终在每个类中定义它。
    • 真正的好处是根本不用定义函数模板!所以你没有任何相关的问题,比如强制。
    猜你喜欢
    • 2016-10-19
    • 2011-05-16
    • 2016-06-23
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2010-12-19
    • 2011-07-15
    相关资源
    最近更新 更多