c++ - 非原始盒装类型的运算符

标签 c++ templates c++11 boxing

我有以下类定义:

template <typename T>
class MyBox {
public:
    MyBox(T value) { _value = value; }
    operator T() const { return _value;  }
private:
    T _value;
};

typedef MyBox<int> MyInt;
typedef MyBox<std::string> MyString;

当我尝试像这样在我的 typedef 上使用运算符时

bool first = MyInt(1) == MyInt(1);    // works
bool second = std::string(MyString("a")) == std::string(MyString("a"));    //works
bool third = MyString("a") == MyString("a");   // does not compile

编译器提示第三次比较

no operator "==" matches these operands. operand types are: MyString == MyString

任何其他非原始装箱都会发生这种情况(例如 MyBox<float> 有效但 MyBox<std::map<int,int> > 无效。为什么会这样?

这对我来说尤其不清楚,因为对于第一次和第二次比较,operator T()使用 - 为什么不能为 MyString 自动完成还有吗?

更新:除了为每个非原始模板提供特定的运算符之外,是否有一个简单的解决方案?以及如何处理 MyString("a") == std::string("a")

最佳答案

为什么它适用于内置类型,但不适用于自定义类型的原因在以下 SO 问题中得到了回答:using user-defined conversions with implicit conversions in comparisons .简而言之,这是因为模板推导类型不会发生类型转换。而内置 operator==对于 int不是模板(因此可以在使用 MyBox<int> 时使用类型转换找到),operator==对于 std::string是一个模板。

但是上面提到的问题并没有详细说明如何解决这个问题。方法如下:添加以下免费功能

template<class T>
bool operator==(const MyBox<T>& lhs, const MyBox<T>& rhs) {
    return static_cast<const T&>(lhs) == static_cast<const T&>(rhs);
}

template<class T>
bool operator==(const MyBox<T>& lhs, const T& rhs) {
    return static_cast<const T&>(lhs) == rhs;
}

template<class T>
bool operator==(const T& lhs, const MyBox<T>& rhs) {
    return lhs == static_cast<const T&>(rhs);
}

关于c++ - 非原始盒装类型的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36062573/

相关文章:

C++ 数组循环问题仍然需要帮助

c++ - 在变量声明中使用 for 循环

html - 如何使用 django 复选框触发函数

c++ - 构造函数参数的条件

c++ - std::future 是否支持多态?

c++ - OpenCV c++ Mat MADNESS

c++ - 在图像/opencv/c++ 中获取检测到的圆的中心

c++ - 在结构部分特化中使用 SFINAE 捕获仿函数

C++ 将方法指针作为模板参数传递

c++ - 了解 move 构造函数、std::move 和析构函数