Re: [問題] 物件繼承與實作的問題 問題在文末
※ 引述《chrisdar (克里斯)》之銘言:
: 如果我將
: const int &StartSameWidthLine<T>::GetX2(void) const
: 改成
: const int StartSameWidthLine<T>::GetX2(void) const
: 那麼就違反 沒有完成所有從 LineInterface<T> 繼承而來的Pure virtual function
: 如果我將
: const int &LineInterface<T>::GetX2(void) const
: 改成
: const int LineInterface<T>::GetX2(void) const
: 那麼就對 StartEndLine<T> 來說這是不必要的複製
: 請問我該怎麼做呢?
你可以用 type trait 的技巧
讓 LineInterface<T> 可以針對不同型別的 T 去產生不同的界面
template <typename T>
struct ReturnType {
// 預設情況下,我們用 const T& 來當 return type
typedef const T& type;
};
template <typename T>
class LineInterface {
public:
...
typedef typename ReturnType<T>::type return_type;
virtual return_type GetX1() const = 0;
virtual return_type GetX2() const = 0;
};
// 重點來了:對於 int 之類的內建型別,可以直接回傳 value type
// 我們用 template specialization 達到這點
template<>
struct ReturnType<int> {
typedef int type;
};
所以當你寫 LineInterface<int> 的時候,其中的 return_type 會是 int 而不是
const int&,而當你用另一個自訂的 class 去具現化 LineInterface 時,就會改
用 const reference 當作 GetX1() 與 GetX2() 的 return type。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.87.151.2
推
04/30 15:56, , 1F
04/30 15:56, 1F
→
04/30 18:21, , 2F
04/30 18:21, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):