【发布时间】:2018-12-22 17:08:55
【问题描述】:
我有一个类A 和一个类B,它们都是带有类型参数T 的泛型。 A<T> 的对象可以转换为 B<T>。我在B 上有一个通用运算符重载,我希望能够调用A 对象和B 对象,其中A 对象被隐式转换。
当我尝试这个时它不会编译:
template <typename T>
class A {};
template <typename T>
class B {
public:
B() {}
B(const A<T> &a) {}
};
template <typename T>
B<T> operator*(const B<T> &obj1, const B<T> &obj2) {
return B<T>(); // doesn't matter
}
int main() {
A<int> objA;
B<int> objB;
B<int> combined1 = objA * objB; // error: operator* isn't defined on these types
B<int> combined2 = static_cast<B<int>>(objA) * objB; // fine
return 0;
}
但是,当 A 和 B 不是通用的时,它可以正常工作:
class A {};
class B {
public:
B() {}
B(const A &a) {}
};
B operator*(const B &obj1, const B &obj2) {
return B(); // doesn't matter
}
int main() {
A objA;
B objB;
B combined1 = objA * objB; // fine
B combined2 = static_cast<B>(objA) * objB; // also fine
return 0;
}
这是为什么?使运算符重载泛型是否意味着无法推断类型?
【问题讨论】:
-
C++ 中没有“通用”类,
A、B、A<T>和B<T>都不是类型。 -
是的,我的术语可能不正确,但我希望意思清楚。
标签: c++ templates operator-overloading implicit-conversion