【问题标题】:Friending template function from multiple classes来自多个类的交友模板函数
【发布时间】:2015-03-11 23:31:20
【问题描述】:

我有这个代码:

template<typename T> T f() {
// ...
}

class A {
    friend A f();
};

class B {
    friend B f();
};

我收到ambiguating new declaration of ‘B f()’ 错误。

但是,如果我将代码更改为以下

template<typename T> void f(T arg) {
// ...
}

class A {
    friend void f(A);
};

class B {
    friend void f(B);
};

程序编译良好。

谁能帮我找出问题所在?

【问题讨论】:

    标签: c++ function oop friend friend-function


    【解决方案1】:
    friend A f();
    

    这一行声明非模板函数A f()存在并且是类的朋友。 这与f&lt;A&gt;() 的功能不同——它是一个全新的功能。

    friend B f();
    

    这一行声明了另一个非模板函数,其名称相同,但返回类型不同。你不能重载函数的返回类型,所以这是禁止的。

    这些友元声明都没有引用您的模板函数,在您的第二个示例中,两个友元声明仍然不引用先前声明的模板函数;它们引用了其他一些非模板函数,就像您的第一个示例中的朋友声明一样。

    这可能是你的意思:

    class A {
        friend A f<A>();
    };
    
    class B {
        friend B f<B>();
    };
    

    并且,修正你的第二个例子:

    class A {
        friend void f<A>(A);
    };
    
    class B {
        friend void f<B>(B);
    };
    

    【讨论】:

      猜你喜欢
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      • 2011-07-30
      • 1970-01-01
      • 2011-07-15
      • 2011-02-18
      相关资源
      最近更新 更多