在类之外为模板类声明非模板朋友功能 [英] Declare non-template friend function for template class outside the class

查看:101
本文介绍了在类之外为模板类声明非模板朋友功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下非模板代码效果很好:

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

但是,如果我在此代码中将类作为模板:

But if I make classes in this code templated:

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

某种出现问题:

错误:"operator +"(操作数类型为"A< int>")不匹配

error: no match for 'operator+' (operand type is 'A<int>')

是否可以为类外的模板类声明非模板朋友功能(就像我对上面的非模板类所做的那样)?

Is it possible to declare non-template friend function for template class outside the class (as I did for non-template classes above)?

我可以通过为A<T>参数添加模板运算符来解决此问题,在里面调用friend函数,但这并不有趣.

I can solve the problem by adding template operator for A<T> argument and call friend function inside, but it is not interesting.

UPD:

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

Another workaround (inspired by R Sahu's answer) is add friend declaration for class A:

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

但是此给出了警告,我不知道如何解决正确.

but this gives a warning, and I don't know how to fix it correctly.

推荐答案

是否可以在类之外为模板类声明非模板朋友功能(就像我对上面的非模板类所做的那样)?

Is it possible to declare non-template friend function for template class outside the class (as I did for non-template classes above)?

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

Yes, it is possible. However, what you probably need is a function template too, and make sure that operator+<int> is a friend of A<int>, operator+<double> is a friend of A<double>, etc.

请参见 https://stackoverflow.com/a/35854179/434551 了解如何完成此操作.

See https://stackoverflow.com/a/35854179/434551 to understand how that can be done.

这篇关于在类之外为模板类声明非模板朋友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆