【问题标题】:Custom types, type conversions making operators conflict?自定义类型,类型转换使运算符冲突?
【发布时间】:2014-05-16 02:01:51
【问题描述】:

我正在创建一个自定义类型。理想情况下,它将尽可能与基本类型互换。为此,我重载了类上的所有运算符,并提供了一个模板构造函数来接受所有基本类型。混合类型的评估总是提升为我的自定义类型。

auto result = 5 / mycustomtype * 2.0f; // result is of type MyCustomType

现在我提供了 int、float 和 double 运算符的实现。理想情况下,类型转换应该像用户期望的那样对任何类型起作用。

添加类型转换运算符让我陷入了一个奇怪的境地:

带代码:

if ( mycustomtype > 5 ) { ... }

编译器看到了很多可能性,包括这个例子:

if ( mycustomtype > MyCustomType( 5 ) ) { ... }

if ( (int)mycustomtype > 5 ) { ... }

因此,对于它可以转换为的每种可能的类型组合,它都会给我一个错误。我理解为什么它有所有这些选项,但我不知道如何解决这个问题。简单的出路是不支持这种方式的类型转换,而是提供如下接口:

auto f = mycustomtype.As< float >()

不过,如果我能把蛋糕也吃掉,那就太好了。

PS:示例错误输出--

c:\...\MyType.cpp(106): error C2666: 'MyType< template params >::operator >=' : 4 overloads have similar conversions
      with
      [
          template specializations...
      ]
      c:\...\MyType.h(63): could be 'bool MyType<...>::operator >=(const MyType<...> &) const'
      with
      [
          template specializations...
      ]
      or       'built-in C++ operator>=(float, double)'
      or       'built-in C++ operator>=(int, double)'
      or       'built-in C++ operator>=(double, double)'
      while trying to match the argument list '(MyType, double)'

【问题讨论】:

    标签: c++ operator-overloading typecast-operator


    【解决方案1】:

    使用 C++11,您可以将类型转换运算符 operator int() {...} 标记为 explicit(参见 here)。

    因此您要么必须使用 C++11 和显式转换,要么忘记这些类型转换运算符。

    顺便说一句,在C++11中也有user-defined literals

    MyType operator"" _mytype (unsigned long long n) {
        return MyType{n};
    }
    

    你可以这样写:

    if(mycustomtype > 5_mytype) { ... }
    

    【讨论】:

    • 不幸的是,我使用的是 VS2012,它似乎不支持显式运算符。公司标准仍然是 VS2012,所以升级不是一个选项。感谢您的回答 :) 我不知道运营商可以是明确的。 C++11 中有很多好东西!
    • 在提出这个问题之前和之后进行了一些非常详尽的搜索之后,似乎 Danvil 是正确的。明确类型转换运算符似乎是唯一的方法。我想我会放弃对它们的支持,直到我们使用能够做到这一点的编译器。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 2020-03-17
    相关资源
    最近更新 更多