Very simplified example (nevermind what the class A
and operators are doing, it's just for example):
#include <iostream>
using namespace std;
template <bool is_signed>
class A {
public:
// implicit conversion from int
A(int a) : a_{is_signed ? -a : a}
{}
int a_;
};
bool operator==(A<true> lhs, A<true> rhs) {
return lhs.a_ == rhs.a_;
}
bool operator==(A<false> lhs, A<false> rhs) {
return lhs.a_ == rhs.a_;
}
int main() {
A<true> a1{123};
A<false> a2{123};
cout << (a1 == 123) << endl;
cout << (a2 == 123) << endl;
return 0;
}
This works.
But if I replace two operator==
's (with same body) with template:
template <bool is_signed>
bool operator==(A<is_signed> lhs, A<is_signed> rhs) {
return lhs.a_ == rhs.a_;
}
, its compilation produces errors:
prog.cpp: In function ‘int main()’:
prog.cpp:31:14: error: no match for ‘operator==’ (operand types are ‘A<true>’ and ‘int’)
cout << (a1 == 123) << endl;
~~~^~~~~~
prog.cpp:23:6: note: candidate: ‘template<bool is_signed> bool operator==(A<is_signed>, A<is_signed>)’
bool operator==(A<is_signed> lhs, A<is_signed> rhs) {
^~~~~~~~
prog.cpp:23:6: note: template argument deduction/substitution failed:
prog.cpp:31:17: note: mismatched types ‘A<is_signed>’ and ‘int’
cout << (a1 == 123) << endl;
^~~
Is it possible to use template here? Can I use C++17 user-defined template deduction guides somehow? Or anything else?
Implicit conversions are not considered in template argument deduction, which causes the deduction for is_signed
fails on the 2nd function argument.
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
If you always use the operator==
in the style like a1 == 123
, i.e. an A<is_signed>
is always used as the 1st operand, you can exclude the 2nd function parameter from the deduction. e.g.
template <bool is_signed>
bool operator==(A<is_signed> lhs, std::type_identity_t<A<is_signed>> rhs) {
return lhs.a_ == rhs.a_;
}
LIVE
PS: std::type_identity
is supported since C++20; even it's not hard to implement one.
Another alternative is friend
function, so the function is not template, but use the template argument:
template <bool is_signed>
class A {
public:
// implicit conversion from int
A(int a) : a_{is_signed ? -a : a}
{}
int a_;
friend bool operator==(const A& lhs, const A& rhs) {
return lhs.a_ == rhs.a_;
}
};
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With