简体   繁体   中英

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

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. 0 is always going to be a valid value as long as size_type is a sensible & correct size-measuring type.

Given that your template says that its an unsigned int whats wrong with

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*/);

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