【发布时间】: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