Avoid Overuse of Conversion Functions

C++ Primer 4/e在Conversions and Class Types這個地方有一個警告:『As with using overloaded operators, judicious use of conversion operators can greatly simplify the job of a class designer and make using a class easier. However, there are two potential pitfalls: Defining too many conversion operators can lead to ambiguous code, and some conversions can be confusing rather than helpful.

The best way to avoid ambiguities is to ensure that there is at most one way to convert one type to another. The best way to do that is to limit the number of conversion operators. In particular there should be only one conversion to a built-in type.

Conversion operators can be misleading when they are used where there is no obvious single mapping between the class type and the conversion type. In such cases, providing a conversion function may be confusing to the user of the class.

As an example, if we had a class that represented a Date, we might think it would be a good idea to provide a conversion from Date to int. However, what value should the conversion function return? The function might return the julian date, which is the sequence number of the current date starting from 0 as January 1. But should the year precede the day or follow it? That is, would January 31, 1986 be represented as 1986031 or 311986? Alternatively, the conversion operator might return an int representing the day count since some epoch point. The counter might count days since January 1, 1971 or some other starting point.

The problem is that whatever choice is made, the use of Date objects will be ambiguous because there is no single one-to-one mapping between an object of type Date and a value of type int. In such cases, it is better not to define the conversion operator. Instead, the class ought to define one or more ordinary members to extract the information in these various forms.』

中文版的這樣寫:『就像重載運算子一樣,明智使用轉換運算子可以大大減輕classes設計者的工作,並使classes更易被使用。然而它有兩個潛在缺點:定義太多轉換運算子容易導致曖昧不明的程式,而且某些轉換容易讓人迷惑,並非對用戶絕對有利。

避免歧義的最佳辦法是,保證「某型別轉換為另一型別」最多只有一條途徑。欲這麼做,最好的方法是限制轉換運算子的數目。尤其「轉換至內建型別」更應該只有一種。

當class型別和目標型別之間無明顯的唯一映射時,使用轉換運算子會令人誤解。這種情況下提供轉換函式可能會讓class用戶深感迷惑。

舉個例子,如果我們有個Date class,我們可能認為提供「從Date到int」的轉換是不錯的主意。然而這個函式應該返回什麼值呢?它可以返回所謂julian date,那是將月份從0起算的當前日期序號。但年應該在日之前或之後呢?也就是說1986年1月31日應該記為1986031還是311986?另一個方式是返回int,代表從某個紀元起算的日期序號,也許是從1971年1月1日或其他起點起算。

問題是,無論如何選擇,由於Date和int之間沒有唯一的映射關係,使用Date物件時仍會出現歧義。這種情況下最好不要定義轉換運算子,應該定義一或多個一般成員函式,用以從不同形式中摘取資訊。』

轉換函式我覺得很好用喔!不過本人為實做過。 😆

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

1 則留言

  1. I finally decided to write a comment on your blog. I just wanted to say good job. I really enjoy reading your posts.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *