无法为泛型类型创建运算符==?

发布于 2024-08-05 13:38:04 字数 1097 浏览 6 评论 0原文

我有一个通用范围类,我正在尝试添加一个比较运算符,以便我可以测试一个范围是否等于另一个范围。它无法编译,我不知道如何解决它所抱怨的问题。我错过了一些明显的事情吗?这是代码片段:

generic<typename T>
public ref class Range
{
protected:
    T m_min;
    T m_max;
public:

    ...
    ...

    bool operator==(Range<T>% rhs) 
    {
        return ( m_min == rhs.m_min ) && ( m_max == rhs.m_max );
    }
};

...无法编译并出现以下错误:

1>c:\projects\Utils.h(47) : error C2676: binary '==' : 'T' does not define this operator or a conversion to a type acceptable to the predefined operator

我是否需要为要重载的每种类型定义转换(我正在使用 Int32 实例化)?我希望避免这种事情,因为它会损害使用泛型。

[编辑] 我有一个实例化如下:

Range<Int32> a = Range<Int32>(0,5);
Range<Int32> b = Range<Int32>(1,3);

if( Int32(2) != Int32(4) )
{
    printf("Int32 supports != operator");
}

if( a != b )
{
    printf("A != B : SUCCESS");
}
else
{
    printf("A == B : FAIL");
}

...除了上述错误之外,它可以正常编译。如果我将每个值转换为 Int32 它会编译,但实际上我想让类尽可能通用(即不必为每种类型重载)。我想我可以对每种类型进行子类化并在那里执行重载运算符,但解决方案并不像我第一次发现泛型时所预期的那样整洁;-)

I've got a generic range class and I'm trying to add a comparison operator so I can test whether one range is equal to another. It fails to compile and I'm not sure how to fix the issues it's complaining about. Have I missed something obvious? Here's a snippet of the code:

generic<typename T>
public ref class Range
{
protected:
    T m_min;
    T m_max;
public:

    ...
    ...

    bool operator==(Range<T>% rhs) 
    {
        return ( m_min == rhs.m_min ) && ( m_max == rhs.m_max );
    }
};

...which fails to compile with the following error:

1>c:\projects\Utils.h(47) : error C2676: binary '==' : 'T' does not define this operator or a conversion to a type acceptable to the predefined operator

Do I need to define conversions for each type that I want to overload (I'm using an Int32 instantiation)? I was hoping to avoid that sort of thing as it rather detracts from using generics.

[Edit] I've got an instantiation as follows:

Range<Int32> a = Range<Int32>(0,5);
Range<Int32> b = Range<Int32>(1,3);

if( Int32(2) != Int32(4) )
{
    printf("Int32 supports != operator");
}

if( a != b )
{
    printf("A != B : SUCCESS");
}
else
{
    printf("A == B : FAIL");
}

...which compiles okay aside fromt he aforementioned errors. If I convert each value to an Int32 it compiles, but really I'd like to keep the class as generic as possible (i.e. not havnig to overload for each and every type). I guess I could subclass for each type and do the overloaded operators there, but the solution is less neat than I had expected when I first discovered generics ;-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

玩套路吗 2024-08-12 13:38:04

您不能将泛型类型的值与 == 运算符进行比较,因为并非所有值类型都保证实现它。

例如,此代码示例失败并显示错误“运算符 '==' 无法应用于类型为 'Test.MyStruct' 和 'Test.MyStruct' 的操作数。

struct MyStruct { }

class Tester {
    void Go()
    {
        bool b = new MyStruct() == new MyStruct();
    }
 }

You cannot compare values of a generic type with an == operator because not all value types are guaranteed to implement it.

For example, this code sample fails with error "Operator '==' cannot be applied to operands of type 'Test.MyStruct' and 'Test.MyStruct'.

struct MyStruct { }

class Tester {
    void Go()
    {
        bool b = new MyStruct() == new MyStruct();
    }
 }
夏了南城 2024-08-12 13:38:04

在标准 C++ 中,

template< class T >
class Range {

    bool operator==(Range const & rhs) const {
        return ( m_min == rhs.m_min ) && ( m_max == rhs.m_max );
    }
};

只要类型 T 有运算符 ==,它就可以工作,

但这显然不是标准 C++,即 generic,即 public ref class >,Range%

寻找一些关于generic事物的特殊规则,我猜他们对类型T施加了比标准模板更多的限制。

In standard C++ you would write

template< class T >
class Range {

    bool operator==(Range const & rhs) const {
        return ( m_min == rhs.m_min ) && ( m_max == rhs.m_max );
    }
};

and it would work as long as the type T has an operator==

But this is obviously not standard C++, the generic, thing the public ref class, the Range<T>%

Look for some special rules regarding generic things, I would guess they put more constrains on the type T than a standard template.

夜司空 2024-08-12 13:38:04

至少在 VS2005 中,需要的是:

generic<typename T> where T: IComparable, IEquatable<T>
public ref class Range {
    ...
};

这会导致编译器接受 == 运算符。我没有测试 Range 类,但它对于类的以下静态方法应该可以正常工作:

generic <class K, class V> where V: IComparable, IEquatable<V>
static
K
KeyForValue(Collections::Generic::IDictionary<K,V>^ src, V value) {
    for each (Collections::Generic::KeyValuePair<K,V>^ kvp in src) {
        if (kvp->Value==value) return kvp->Key ;
    }
    throw gcnew Collections::Generic::KeyNotFoundException() ;
    return K() ;
}

In VS2005 at least, what's needed is:

generic<typename T> where T: IComparable, IEquatable<T>
public ref class Range {
    ...
};

This leads to the compiler accepting the == operator. I didn't test the Range class, but it works as it should for the following static method of a class:

generic <class K, class V> where V: IComparable, IEquatable<V>
static
K
KeyForValue(Collections::Generic::IDictionary<K,V>^ src, V value) {
    for each (Collections::Generic::KeyValuePair<K,V>^ kvp in src) {
        if (kvp->Value==value) return kvp->Key ;
    }
    throw gcnew Collections::Generic::KeyNotFoundException() ;
    return K() ;
}
寒江雪… 2024-08-12 13:38:04

据我所知,您可以使用“Range”而不是“Range”当 T 与实例化类模板的类型相同时。尝试一下。

离题了,但我会返回一个 const bool,并让该函数也成为 const。除非您知道需要保护,否则还将受保护更改为私有。

我认为“%”是“&”的拼写错误?编辑:除了我刚刚注意到 c++-cli 标签,所以这可能是 C++/CLI 中存在的一些疯狂的运算符,遗憾的是我对此一无所知:)

As far as I know, you can use "Range" instead of "Range<T>" when T is the same type as the type the class template is instantiated with. Give that a try.

Off-topic, but I'd return a const bool, and make that function const too. Also change protected to private unless you know you need protected.

And I assume that '%' is a typo for '&'? EDIT: except I just noticed the c++-cli tag, so that's probably some crazy operator present in C++/CLI, which sadly I know nothing about :)

心如荒岛 2024-08-12 13:38:04

您是否尝试过添加 where IComparable 约束?

generic<typename T> where T: IComparable
public ref class Range  {
....

Have you tried adding a where IComparable constraint?

generic<typename T> where T: IComparable
public ref class Range  {
....
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文