[英]C++ operator overloading resolution ambiguity
我試圖將老式的C ++代碼庫從gcc 3.2遷移到gcc 4.1,因為我遇到了一些問題。 在所有問題中,以下內容使我毫無頭緒(我想我花了太多時間在Java上,或者我可能忘記了C ++的基本知識:-P)。
我有一個模板課
template < class T > class XVector < T >
{
...
template < class T > T
XVector < T >::getIncrement ()
{
...
}
template < class T > int
XVector < T >::getValue (size_t index, T& value)
{
...
//The problematic line
value = (T) (first_value + getIncrement())
* (long) (index - first_index);
....
}
}
此類基於STL std :: vector。 我有第二個類TypeValue及其定義如下,它可以容納int,long及其無符號變體之一,float,double,std :: string中的一個。 也使幾乎所有可能的運算符過載。
class TypeValue
{
union
{
long* _int_value;
double* _real_value;
string* _text_value;
} _value;
TypeValue();
explicit TypeValue(long _long);
explicit TypeValue(int _int);
explicit TypeValue(unsigned long _ulong);
...
//similarly for all the remaining supported types.
TypeValue(const TypeValue& ) //Copy constructor
virtual TypeValue& operator=(const TypeValue &rhs);
TypeValue& operator+ (TypeValue& )const;
TypeValue& operator* (TypeValue& )const;
...
//For all the basic operators
operator long() const;
operator int() const;
operator unsigned long() const;
operator unsigned int() const;
...
}
最后,我還有另一個類,稱之為build_breaker,它創建一個對象為XVector < TypeValue > a_variable;
。 現在,當我在gcc 3.2上進行編譯時,此編譯將沒有任何問題。 但是,當我嘗試在gcc 4.1上進行編譯時,我得到了錯誤,提示類XVector
中的operator*
大量重載,而候選對象是
operator*(long int, long int) operator*(int, long int) operator*(long unsigned int, long int) operator*(unsigned int, long int) operator*(double, long int) operator*(float, long int)
如果編譯器說在找到T * long的匹配項時遇到問題,那是有道理的,但是,為什么它試圖將其類型轉換為本機類型,然后執行算術運算呢? 請幫我。
提前致謝。
第二種操作數類型是long [int]
。 我希望第一個是TypeValue
,但是沒有運算符*
可以接受這兩個確切類型。 但是,該運算符還有許多其他類型組合,編譯器可以通過對第一個操作數進行隱式轉換來選擇這些組合。 該語言允許編譯器執行此操作以嘗試找到匹配項。
但是,它應該選擇眾多轉換中的哪一個? 編譯器無法選擇int
是否比long int
。 (您可能會爭辯說,由於第二個操作數是long int
,所以它應該是首選的轉換目標,但這不是事情的工作方式。)
因此,有一些建議:首先,不要提供太多的隱式轉換。 由於該類只能容納long
, double
和string
,因此這些是我提供的僅有的三個轉換。 僅此一項可能無法解決您的問題,但可能會減少錯誤輸出的大小並使其他內容更易於管理。
不要將(index - first_index)
轉換為long
類型,而應考慮將其轉換為T
(即TypeValue
)類型,因為這似乎是您真正想執行的操作。
我將所有轉換運算符更改為命名函數,以便:
operator long() const;
變成
long ToLong() const;
通過強制轉換運算符進行的隱式對話會引起各種問題,而我自己的編程標准禁止使用它們。
我們需要知道什么是T。看起來您正在使用某種類型(例如,無符號字符)實例化一個XVector,該類型可以轉換為您看到的所有這些類型,並且編譯器不知道該選擇哪種類型。 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.