带转换运算符的模板参数
template parameter with conversion operator
#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
}
有人可以详细说明为什么第一个版本不起作用吗?也就是说为什么func中的二元运算符==不使用转换运算符int将绑定到Base的模板参数转换为int?
是否可以仅通过修改 class Base 来使版本 1 工作?
您的 func
通过 const 引用接受其参数,但是 Base
class 中定义的 operator int()
是一个非常量成员函数。将其标记为const成员函数,如下所示,您的代码将通过编译:
#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
}
#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
}
有人可以详细说明为什么第一个版本不起作用吗?也就是说为什么func中的二元运算符==不使用转换运算符int将绑定到Base的模板参数转换为int?
是否可以仅通过修改 class Base 来使版本 1 工作?
您的 func
通过 const 引用接受其参数,但是 Base
class 中定义的 operator int()
是一个非常量成员函数。将其标记为const成员函数,如下所示,您的代码将通过编译:
#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
}