在类

时间:2016-03-15 20:51:34

标签: c++ templates friend-function

以下非模板代码works well

struct A { };

struct B
{
    B() {}
    B(const A&) {}
    friend B operator+(const B&) { return B(); }    
};

B operator+(const B&);

int main()
{
    A a;
    B b;
    +b;
    +a;
}

但是,如果我在这段代码中创建模板:

template <class T>
struct A { };

template <class T>
struct B
{
    B() {}
    B(const A<T>&) {}
    friend B operator+(const B&) { return B(); }    
};

template <class T>
B<T> operator+(const B<T>&); // not really what I want 

int main()
{
    A<int> a;
    B<int> b;
    +b;
    +a;
}

某种troubles appear

  

错误:不匹配&#39;运营商+&#39; (操作数类型是&#39; A&lt; int&gt;&#39;)

是否可以为类外的模板类声明非模板友元函数(正如我上面的非模板类所做的那样)

我可以通过为A<T>参数添加template operator并在里面调用friend函数来解决问题,但这并不重要。

UPD:

另一种解决方法(受R Sahu's answer启发)是为类friend添加A声明:

template <class T>
struct A { 
    friend B<T> operator+(const B<T>&);
};

gives a warning,我不知道如何正确修复它。

2 个答案:

答案 0 :(得分:1)

  

是否可以为类外的模板类声明非模板友元函数(就像我上面的非模板类所做的那样)?

是的,有可能。但是,您可能还需要一个功能模板,并确保operator+<int>friend A<int>operator+<double>friend A<double> 1}}等等。

请参阅https://stackoverflow.com/a/35854179/434551了解如何做到这一点。

答案 1 :(得分:0)

是否可以在课堂外为模板类声明非模板友元函数?

答案:是的,但是......你需要为你使用的每个组合声明一个函数:

这个功能解决了你的声明问题:

A<int> operator+(const A<int>&) { return A<int>(); }

但是,如果你使用A&lt; double&gt;,你需要明确声明其他函数:

A<double> operator+(const A<double>&) { return A<double>(); }

不是好朋友,因为在结构中所有成员都是公开的

相关问题