【发布时间】:2018-01-25 08:44:39
【问题描述】:
我有一个结构模板 A<x> 和一个带有 int 的 + 运算符。
#include <iostream>
template<int x>
struct A{
int a;
};
template<int x>
int operator+(A<x> a, int b){
return a.a+b;
}
我创建了一个结构模板B<x>,可以转换为A<x>。
template<int x>
struct B{
int b=3;
operator A<x>(){
return {b+10};
}
};
现在我希望在调用B<x> + int 时将B<x> 转换为A<x>。
int main(){
std::cout<<(A<12>{9}+10)<<std::endl;//OK
std::cout<<(B<12>{9}+10)<<std::endl;//Error
return 0;
}
我读了Implicit conversion when overloading operators for template classes并写了
template<int x>
struct B{
int b=3;
operator A<x>(){
return {b+10};
}
friend int operator+(A<x> a, int b);
};
,但它不起作用,因为声明的 friend int operator+(A<x> a, int b) 与 template<int x> int operator+(A<x> a, int b) 不匹配。
我看了C++ - How to declare a function template friend for a class template,做了朋友声明模板,但是因为模板参数无法推导,所以没用。
当然,我可以为 A 和 B 都写 operator+,但是我有几十个运算符,我不想这样做。
这样做的正确方法是什么?
【问题讨论】:
-
我认为,你不能使用相同的运算符,要么在 B 中声明模板友元运算符,要么除非 B 会从 A 派生
-
你不能制作
operator+模板吗? -
@W.F.是的,它没有在提供的代码中声明为模板,它的模板应该在类中定义为与类模板实例同时存在。如果 B 派生自它,它将能够使用为 A 定义的运算符。
-
你能碰
A吗? -
@T.C.是的,我也可以改变 A。
标签: c++ templates operator-overloading c++14 friend-function