模板类的非常量参数
我有一个来自 API 的模板类,它是用类似的东西实例化的。
位域<长度>目的;
问题是长度变量仅在运行时才知道。
错误:“长度”不能出现在常量表达式中 ->这是错误消息
有什么建议吗?
I have a template class from an API that is instantiated with something like this.
BitField< length > object;
The problem is that length variable is only known at runtime.
error: 'length' cannot appear in a constant-expression -> this is the error message
Any suggestions ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
模板严格来说是一个编译时概念。编译后,它们被嵌入并且无法更改。您不能使用仅在运行时已知的信息作为模板参数。
解决这个问题的一种方法是,如果您知道位集大小的上限,并将该常量用于模板化位集结构。如果上限大得不可接受,则必须使用不同的数据结构,类似于动态调整大小的向量。
Templates are strictly a compile-time concept. After compilation, they're baked in and cannot be changed. You cannot use information only known at runtime as a template parameter.
One way around this is if you known an upper-bound for the size of your bitset, and use that constant for your templated bitset structure. If the upper-bound is unacceptably large, you'll have to use a different data structure, something akin to vector which is dynamically sized.
您必须使用另一个允许在运行时设置长度的位字段数据结构。
You have to use another bitfield data structure that allows setting length at runtime.
这取决于您需要的运行时灵活性程度。如果您正在处理一小部分场景,您可以为您的可能性定义常量并有条件地实例化。
编辑:谢谢约翰,没有实际理由使用
#define
而不是static const
。我很尴尬我的C出现了。也许人们会认为这是键盘故障。显然,这会变得异常快。这是一种非常程序化的方法,如果您的逻辑需要真正动态,那么这种操纵很快就会失去其价值。
编辑:
让我说得很明显。如果您真正被这个特定的 API 和数据结构所束缚,并且您需要处理的情况很少,那么这是一种方法。换句话说,如果“使用其他东西”(老实说,这是一个更好的答案)根本行不通。
我也同意其他人的观点,如果浪费的空间不是什么大问题,那么为您的 BitField 定义一个适用于所有预期情况的上限是一个更好的主意。
It depends on the degree of runtime flexibility you need. If you are dealing with a small set of scenarios, you could define constants for your possibilities and conditionally instantiate.
EDIT: Thanks John, no actual justification for
#define
overstatic const
. I'm embarrassed that my C is showing. Maybe people will believe it was a keyboard malfunction.Obviously, this gets unwieldly quick. This is a very procedural approach, and if your logic needs to be truly dynamic, this kind of rigging quickly loses its worth.
EDIT:
Let me be explicitly obvious. This is an approach if you are truly locked into this specific API and data structure, and the set of cases you need to handle are small. In other words, if "use something else" (which is, honestly, a better answer) simply will not work.
I also agree with others that defining an upper bound to your
BitField
which will work for all expected cases is a better idea, if the wasted space is not a big deal.