Reputation: 3171
#include <iostream>
template <typename T1, typename T2>
bool func(const T1& t, const T2& t2) {
return t == t2;
}
class Base {
public:
bool operator ==(const Base&) const { return true;}
Base(int y) : x(y) {}
operator int() {
return x;
}
int x;
};
int main() {
func<long, Base>(4L, Base(5)); // not ok
func<long, long>(4L, Base(5)); //ok
}
Can somebody elaborate why the first version does not work? In otherwords why does the binary operator == in func not use the conversion operator int to convert the template parameter bound to Base into int?
Is there anyway to make version 1 work by only modifying the class Base?
Upvotes: 1
Views: 103
Reputation: 5352
Your func
accepts its parameters by const reference, but the operator int()
defined in your Base
class is a non-const member function. Mark it as a const member function, as shown below, and your code will compile:
#include <iostream>
template <typename T1, typename T2>
bool func(const T1& t, const T2& t2) {
return t == t2;
}
class Base {
public:
bool operator ==(const Base&) const { return true;}
Base(int y) : x(y) {}
operator int() const {
return x;
}
int x;
};
int main() {
func<long, Base>(4L, Base(5)); // ok now!
func<long, long>(4L, Base(5)); // ok
}
Upvotes: 3