考慮使用標籤結構
struct tagPosition {};
struct tagDirection {};
struct tagGeneric {};
namespace detail
{
template <typename Tag=tagGeneric>
class Vector3
{
// business as usual
};
}
typedef detail::Vector3<tagPosition> Position;
typedef detail::Vector3<tagDirection> Direction;
typedef detail::Vector3<tagGeneric> Vector3;
加分,有轉換操作符/構造:
template <typename Tag=tagGeneric>
class Vector3
{
template <typename OtherTag>
explicit Vector3(const Vector3<OtherTag>& rhs) { /* ... */ }
// template <typename OtherTag>
// operator Vector3<OtherTag>() const { return /* ... */ }
};
如果你喜歡驚險的生活,你可以刪除explicit
關鍵字,或啓用隱式轉換運算符。這將有中能夠使混雜像這樣操作員的決議「好處」:
Position pos;
Direction dir;
Generic gen;
dir = gen + pos; // you see why I call it 'promiscuous'?
我建議(代替)來定義這樣的情況下,明確運營商(無功能:)
Position operator+(const Position& v, const Translation& d) { /* .... */ }
這樣,你的類模型反映了你的類的語義。
C++0x would possibly contain things to enable explicit conversion operators,IIRC:
在轉換構造的情況下,您可以通過聲明爲顯式的N1592 proposal綿延此關鍵字的語義所有轉換運營商構造器來關閉隱式轉換。聲明爲明確的轉換運算符不會執行隱式轉換。相反,程序員必須顯式調用
這樣做的問題是,位置是隱式轉換爲向量(這從技術上來說,矢量現在必須有一個虛析構函數,以便安全地使用) – jalf 2011-06-17 08:20:12
@jalf :即使派生類沒有添加任何數據或方法,虛擬析構函數是否真的需要? – 2011-06-17 08:26:14
jalf:我在我的回答中討論轉換主題 – sehe 2011-06-17 08:27:27