[英]Custom types, type conversions making operators conflict?
我正在創建一個自定義類型。 理想情況下,它將與基本類型盡可能互換。 為此,我重載了該類上的所有運算符,並提供了一個模板化的構造函數以接受所有基本類型。 混合類型的評估始終會提升為我的自定義類型。
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)'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.