简体   繁体   English

Operator==() 模板类的隐式转换

[英]Implicit Conversion of Templated Class for Operator==()

I have a templated class like so:我有一个像这样的模板化类:

struct Base
{
    bool operator==(const Base& other) const {
        return v == other.v;
    }
    int v;
};
struct Abc : public Base
{
    void execute() { /*logic1*/ }
};

struct Def : public Base
{
    void execute() { /*logic2*/ }
};

template <typename T>
class Foo
{
public:
    bool operator==(const Foo& other) const {
        return (a == other.a) && (b == other.b);
    }

    int a;
    T b;
};

This works fine, however I'd like to extend this operator==() method to allow the equality to only be valid if the object passed in is of the same templated type.这工作正常,但是我想扩展这个 operator==() 方法,以允许相等仅在传入的对象具有相同模板类型时才有效。 Here's an example:下面是一个例子:

Foo<Abc> obj1;
Foo<Abc> obj2;
Foo<Def> obj3;

obj1 == obj2; // should be true
obj1 == obj3; // should fail at compile-time or run-time

When I do this:当我这样做时:

bool operator==(const Foo& other) const {
    std::cerr << typeid(other).name() << std::endl;
    return (a == other.a) && (b == other.b);
}

I notice that the instance of the class passed in is implicitly converted into the type of this class.我注意到传入的类的实例被隐式转换为这个类的类型。 I thought about including a member variable on the templated object to distinguish them, but it's a little annoying to have to add an extra variable it feels like I shouldn't need.我想在模板化对象上包含一个成员变量来区分它们,但是不得不添加一个我觉得不需要的额外变量有点烦人。 Is there a better way of achieving this equality test?有没有更好的方法来实现这个平等测试?

As I understand, there exists implicit conversion from Foo<T1> to Foo<T2> .据我了解,存在从Foo<T1>Foo<T2>隐式转换。

Possible solutions are:可能的解决方案是:

  1. Forbid implicit type conversion (use explicit keyword for constructors and cast operators).禁止隐式类型转换(对构造函数和强制转换运算符使用explicit关键字)。

  2. Make operator == templated and use enable_if to allow only possible combinations:使operator ==模板化并使用enable_if仅允许可能的组合:

     template <typename T1, typename = std::enable_if<std::is_same<T, T2>::value>::type> bool operator == (const Foo<T1>& other) const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM