I have a struct template A<x>
and a +
operator with int
.
#include <iostream>
template<int x>
struct A{
int a;
};
template<int x>
int operator+(A<x> a, int b){
return a.a+b;
}
I created a struct template B<x>
, which is convertible to A<x>
.
template<int x>
struct B{
int b=3;
operator A<x>(){
return {b+10};
}
};
Now I want B<x>
to be converted to A<x>
when calling B<x> + int
.
int main(){
std::cout<<(A<12>{9}+10)<<std::endl;//OK
std::cout<<(B<12>{9}+10)<<std::endl;//Error
return 0;
}
I read Implicit conversion when overloading operators for template classes and wrote
template<int x>
struct B{
int b=3;
operator A<x>(){
return {b+10};
}
friend int operator+(A<x> a, int b);
};
, but it didn't work because the declared friend int operator+(A<x> a, int b)
does not match template<int x> int operator+(A<x> a, int b)
.
I read C++ - How to declare a function template friend for a class template and made friend declaration template, but it didn't work because the template parameter couldn't be deduced.
Of course I could write operator+ for both A and B, but I have dozens of operators and I don't want to do it.
What is the correct way to do this?