我已经定义了一个IntWrapper类如下的类:
struct IntWrapper
{
protected:
int value;
public:
explicit IntWrapper() = default;
explicit IntWrapper(const int value) : value(value) {}
bool operator< (const IntWrapper rhs) const { return value < rhs.value; }
bool operator> (const IntWrapper rhs) const { return value > rhs.value; }
bool operator<=(const IntWrapper rhs) const { return value <= rhs.value; }
bool operator>=(const IntWrapper rhs) const { return value >= rhs.value; }
bool operator==(const IntWrapper rhs) const { return value == rhs.value; }
explicit operator int() const { return value; }
};
Run Code Online (Sandbox Code Playgroud)
与类Foo和Bar从继承IntWrapper
struct Foo: IntWrapper
{
using IntWrapper::IntWrapper;
};
struct Bar: IntWrapper
{
using IntWrapper::IntWrapper;
};
Run Code Online (Sandbox Code Playgroud)
我想只比较相同类型的对象.换句话说,我想下面这段给出编译错误,而不是铸造foo和bar到IntWrapper.
const Foo foo(1);
const Bar bar(2);
bool b = foo >= bar;
Run Code Online (Sandbox Code Playgroud)
既然我有许多其他对象喜欢Foo和Bar,有没有办法实现我的结果保持所有的比较运算符IntWrapper?
您可以向您添加虚拟模板,IntWrapper以使比较运算符IntWrapper仅适用于同一类型:
template<class>
struct IntWrapper
{ /* same code */ };
struct Foo : IntWrapper<Foo> { using IntWrapper::IntWrapper; };
struct Bar : IntWrapper<Bar> { using IntWrapper::IntWrapper; };
int main()
{
const Foo foo(1);
const Bar bar(2);
//bool b = foo >= bar; // error: no match for 'operator>=' (operand types are 'const Foo' and 'const Bar')
}
Run Code Online (Sandbox Code Playgroud)