简体   繁体   English

模板初始化中的C ++

[英]C++ in template initialization

Given the following piece of code: 给出以下代码:

template<typename T>
class MyContainer
{
    typedef T value_type;
    typedef unsigned int size_type;

    ...
};

How one should initialize variables using size_type (like loop indexes)? 应该如何使用size_type初始化变量(如循环索引)?
Should it be: 应该是:

for(size_type currentIndex = size_type(0);currentIndex < bound;++currentIndex)

or 要么

for(size_type currentIndex = static_cast<size_type>(0);currentIndex < bound;++currentIndex)

The rationale for the question is to produce code that will still work when type underlying size_type is changed or added to template parameters. 该问题的基本原理是生成代码,当基础size_type类型更改或添加到模板参数时,该代码仍然可以使用。

Thanks... 谢谢...

There are four possibilities I see: 我看到四种可能性:

size_type();
size_type(0);
static_cast<size_type>(0);
0;

I would prefer the last one. 我希望最后一个。 It's concise, and has the same effect as the rest. 简洁明了,与其他功能一样。

You're probably worried that if the type change this won't work, or something. 您可能担心,如果更改类型将无法正常工作,或者发生其他情况。 The thing is, size_type 's are, by convention, unsigned integers. 事实是,按惯例, size_type是无符号整数。 0 is always going to be a valid value as long as size_type is a sensible & correct size-measuring type. 只要size_type是明智且正确的尺寸测量类型,则0始终将是有效值。

Given that your template says that its an unsigned int whats wrong with 鉴于您的模板说它是一个unsigned int,这有什么问题

for(size_type currentIndex = 0;currentIndex < bound;++currentIndex)

?

If you are doing it for reasons of chaging the type at a later date then, personally, I'd definitely go with the construction method (ie The former). 如果您出于以后推迟类型的考虑而这样做,那么就我个人而言,我肯定会采用构造方法(即前者)。

First case look pretty. 第一种情况看起来很漂亮。 Even more you can do following: 您甚至可以执行以下操作:

for(size_type currentIndex = size_type(/*empty*/);

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

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