比率是常数,但如果我想接受不同的比率作为参数怎么办? [英] Ratio<,> is constant, but what if I want to accept different ratios as an argument?
问题描述
也许是一个矛盾的问题:ratio<,> 根据定义, 编译时常量.
Perhaps an oxymoronic question: ratio<,> is, by definition, a compile-time constant.
但是,我想构造具有不同比率的持续时间,这些比率可由我的方法的调用者指定.我猜我应该使用比率和/或持续时间以外的其他东西,但是什么?
However, I would like to construct durations with different ratios that can be specified by the caller of my method. I'm guessing I should be using something other than ratio and/or duration, then, but what?
我想要一个可以在运行时设置的类成员,我希望它的类型为 ratio<,>.在代码中的某个点,该成员被设置/分配,它将被分配一个恒定的比率,但在我的班级中,我不想指定该比率应该是多少.
I want to have, say, a class member that can be set at runtime, and I would like it to be of type ratio<,>. At some point in the code, where this member gets set/assigned, it would be assigned a constant ratio, but in my class, I don't want to specify what that ratio should be.
推荐答案
好的,您需要一个 std::ratio
,可以由调用者指定".共有三种不同的选项:
Ok, you need a std::ratio
which "can be specified by the caller". There are three different options:
- 调用者想要在编译时间期间设置
std::ratio
模板参数.这很简单,只需设置参数,例如使用四分之一 = std::ratio<1, 4>
. - 调用者想要在运行时期间设置
std::ratio
模板参数.这根据定义是不可能的,std::ratio
是一个编译时常量.您必须实现自己的类来在运行时计算比率或使用某种库(我不知道有任何库,欢迎提出建议!). - 调用者只想缩放
std::duration
(这似乎是您使用std::ratio
的目的).然后只需乘以一个数字.
- The caller wants to set
std::ratio
template parameters during compile time. This is trivial, simply set the parameters, e.g.using quarter = std::ratio<1, 4>
. - The caller wants to set
std::ratio
template parameters during runtime. This is not possible by definition,std::ratio
is a compile-time constant. You will have to implement your own class for computing ratios during runtime or use some kind of library (I don't know of any, suggestions welcome!). - The caller merely wants to scale a
std::duration
(which is what you seem to use yourstd::ratio
for). Then just multiply it with a number.
这篇关于比率是常数,但如果我想接受不同的比率作为参数怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!