我想編寫一個模板函數來檢查一些Timestamp屬性(類繼承自Timed
),但也必須適用於沒有時間戳的類型。我發現的最好的(也是相當醜陋的)解決方案如下:根據參數類型製作模板功能代碼的最簡單方法是什麼
class Timed {
protected:
int mTime;
public:
explicit Timed(int time=0): mTime(time){}
int getT() const {return mTime;}
};
template<typename T>
bool checkStale(T const* ptr) const {
return checkStaleImp(ptr, boost::is_base_of<Timed, T>());
}
template<typename T>
template<bool b>
bool checkStaleImp(T const* ptr, boost::integral_constant<bool, b> const &){
return true;
}
template<typename T>
bool checkStaleImp(T const* ptr, boost::true_type const&){
const int oldest = 42;
return (42 <= ptr->getT());
}
這是一個功能的三個功能。是否有更簡單的方法來完成此操作,例如使用boost::is_base_of
或某物。類似於if條件或boost :: enable,如果將函數輸出轉換爲不是從Timed
派生的類的常量類型。不幸的是,解決方案具有虛擬功能。
你爲什麼使用模板? – AJG85 2012-02-07 16:36:15
@ AJG85:實際的功能是類模板的成員(省略了縮寫的例子)所以模板的問題與否已經過時,但是閱讀fernandes的答案我認爲一個更簡單的解決方案是可能的 – Martin 2012-02-07 18:33:43
這是評論。讓你考慮像重載等替代方案。 – AJG85 2012-02-07 18:41:31