作者littleshan (我要加入剑道社!)
看板C_and_CPP
标题Re: [问题] 物件继承与实作的问题 问题在文末
时间Thu Apr 30 15:53:52 2009
※ 引述《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
1F:推 chrisdar:赶紧测试看看 ... 谢谢您 04/30 15:56
2F:→ chrisdar:根据各方的意见 决定采用(#19-JrOLY)方法二 04/30 18:21