简体   繁体   English

C++:Function 参数或模板参数

[英]C++: Function argument or template parameter

I have a class myclass that depends on some int for, say, setting up the size of a vector member.我有一个 class myclass ,它依赖于一些int来设置向量成员的大小。 I can implement that as a non-type template parameter我可以将其实现为非类型模板参数

template<int sz>
class myclass {
...

or或者

class myclass {
...

and then simply use sz as a parameter in the constructor or other class methods.然后在构造函数或其他 class 方法中简单地使用sz作为参数。

Both would work in many cases.两者都可以在很多情况下工作。 In some other cases (eg, if myclass refers to other templated classes or functions using sz as a non-type template parameter), only the first option would work.在其他一些情况下(例如,如果myclass使用sz作为非类型模板参数来引用其他模板化类或函数),则只有第一个选项有效。 In cases where both can work, what are the possible reasons to prefer one or the other?在两者都可以工作的情况下,偏爱其中一个的可能原因是什么?

Besides my new coding in the future, this would also impact in what I do with some code I already have... whether to make efforts in "converting" one type of implementation to the other, or leave it as it is now.除了我未来的新编码之外,这也会影响我对已有代码的处理方式……是努力将一种实现类型“转换”为另一种,还是保持现状。

I am not only asking about the differences (eg, allocation at compile vs. runtime), but also how these differences may make one or the other option preferable.我不仅要询问差异(例如,编译时分配与运行时分配),还要询问这些差异如何使一个或另一个选项更可取。

First, the overlap (“where both can work”) is rather smaller than you might think.首先,重叠(“两者都可以工作”)比您想象的要 You can't make a container of various specializations of a class template (absent type-erasure tricks ).您不能制作包含class 模板的各种专业化的容器(缺少类型擦除技巧)。 Any function that uses myclass for a parameter or return type must, if myclass is a template, either name a specialization or be templated itself.任何使用myclass作为参数或返回类型的 function 如果myclass是模板,则必须命名专业化模板化自身。 Even purely local usage overlaps only if the size is a constant expression.仅当大小是常量表达式时,即使是纯本地使用也会重叠。

If none of these issues have forced your hand, there are performance implications as well.如果这些问题都没有强迫您处理,那么也会对性能产生影响。 Using several instantiations of a class template may increase the binary size, although aggressive inlining may reduce that cost.使用 class 模板的多个实例化可能会增加二进制大小,尽管积极的内联可能会降低成本。 Using a runtime parameter may introduce additional runtime overhead, although aggressive inlining may reduce that too.使用运行时参数可能会引入额外的运行时开销,尽管积极的内联也可能会减少这种开销。 You also can't avoid heap allocation with a single type (unless you impose a maximum capacity—that you always pay for).您也无法避免使用单一类型进行堆分配(除非您施加最大容量——您总是为此付费)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM