接受子类的模板作为对象的模板
Accept Template of Child Class as Template for Object
在Bellow示例中,使用STD :: Chrono库,我正在寻找一种接受基本计时器的持续时间的方法。
template <std::chrono::duration D> //Accept either std::chrono::minute, second, etc...
class myTimer{
}
但是,由于持续时间不符合模板关键字的标准。
template <class T>
class myTimer{
//I could do a static cast, but Duration is only a template used by the children, not an actual class per say.
}
因此,我的问题归结为,最好的解决方案对于更少的代码和更好的可用性是什么?我觉得自己是一个静态的演员,与模板中的一个未知的孩子无法正常工作,但我可能完全错了。
您在这里有很多选择,范围从易于且易于畅通,到极其富裕但多重的工作。
最简单的是仅存储nanoseconds
,而不是模板myTimer
:
class myTimer
{
std::chrono::nanoseconds time_;
...
};
您的构造函数只能采用nanoseconds
。所有"内置"计时单元将隐式转换为nanoseconds
:
myTimer t{3min}; // ok, 180'000'000'000ns
这里唯一的缺点是,每个每个 duration
都会隐式转换为nanoseconds
。也许您希望您的客户能够使用picseconds,1/60s单元或浮点持续时间,或者这里的意图(很难说)是控制计时器内部存储的精度(不是真正必要的,但是你永远不会知道)。然后您可能会移动到模板的解决方案:
从is_duration
模板开始并不是一个不好的起点。即使您最终不在此项目中使用它,它也可能方便:
template <class T>
struct is_duration
: public std::false_type
{};
template <class Rep, class Period>
struct is_duration<std::chrono::duration<Rep, Period>>
: public std::true_type
{};
现在您可以说is_duration<T>{}
,这是一个编译时布尔,可以回答false的正确。您可以(例如)这样使用它:
template <class D,
class = std::enable_if_t<is_duration<D>{}>>
class myTimer
{
D time_;
};
这将使除std::chrono::duration
以外的任何其他内容都无法编译。
您也可以采用不需要is_duration
的方法:
template <class D> class myTimer;
template <class Rep, class Period>
class myTimer<std::chrono::duration<Rep, Period>>
{
};
如果有兴趣探索这条路线,请尝试这两种方式并确定您最喜欢的错误消息。
不要忘记:最适合您的解决方案可能是最简单的:只需使用 nanoseconds
,然后将所有内容都在此上。
相关文章:
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- C++ 将子类的对象添加到父类的向量中
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 对静态分配的子类对象进行静态分配的纯虚拟父类引用是否合法?
- 创建一个函数,该函数使用模板创建类或子类的对象
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- C++接口实现和子类化对象识别
- 如何调用传递给 JNI 'jobject' 的 Java 对象的子类/子类的方法
- 为什么指向基类的指针可以指向子类的对象?
- 如何在 BaseClass 指针数组中存储指向子类对象的指针?
- 当函数返回类型为父类时,如何返回子类的对象?
- 子类对象列表重新解释为基类对象列表?(C++11).
- 如何将字符串(ID)映射到新的子类对象C 的创建
- C++:使用父类运算符函数更新子类对象的继承变量
- 指向子类对象的指针的静态数组出现问题
- 尝试引用子类中的抽象对象时收到编译错误
- cpp 从需要超类对象的函数访问子类对象方法
- 制作可以存储子类对象的超类类型的向量