自定义类型,类型转换会使运营商发生冲突?

时间:2014-04-04 00:09:48

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

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

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)'

1 个答案:

答案 0 :(得分: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) { ... }