簡體   English   中英

自定義類型,類型轉換使運算符發生沖突?

[英]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)'

使用C ++ 11,您可以將類型轉換操作operator int() {...}標記為explicit (請參閱此處 )。

因此,您要么必須使用C ++ 11和顯式轉換,要么就不用考慮這些類型轉換運算符。

順便說一句,在C ++ 11中,還有用戶定義的文字

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

這樣,您可以編寫:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM