tags:

views:

99

answers:

3

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

+1  A: 

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

Goz
+4  A: 

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.

GMan
This seams reasonable but what if I will at some point want to use my own type - MyHugeIntegerType - for example?
Bartłomiej Siwek
@Bartłomiej: Are you planning on making an ill-formed integer type that has no zero?
GMan
@GMan I'm not planing on making an ill-formed integer type but rather consider the possibility to use a type that doesn't implicitly allow for casting from integer types (i.e. has a explicit constructor)
Bartłomiej Siwek
@Bartłomiej: That would make it ill-formed. If it represents an integer, it should be implicitly convertible from one.
GMan
Ok. I guess that I'm planing on making and ill-formed integer type and using it here.
Bartłomiej Siwek
@Bartłomiej: What's your rationale for making the constructor from int explicit?
GMan
@Gman: If, for example, I'm making interval arithmetics I might not want to make conversion form int implicit since You can do sucha a thing in many ways.
Bartłomiej Siwek
A: 

First case look pretty. Even more you can do following:

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