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物件时仍会出现歧义。这种情况下最好不要定义转换运算子,应该定义一或多个一般成员函式,用以从不同形式中摘取资讯。’

转换函式我觉得很好用喔!不过本人为实做过。 😆

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.

Comments are closed.