简体   繁体   中英

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. 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.

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. 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 ). 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. 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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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