我想编写一个模板函数来检查一些 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 if 中类似,用于将函数输出转换为不派生自的类的一种常量Timed
。不幸的是,具有虚拟功能的解决方案不是一种选择。