typedef & template

D

Dmytro

Hi!

This code is ok:

template<class T>
struct Container
{
T x;
typedef int size_type;
size_type size() { return sizeof T; }
};

Why the compiler (VC7) does not compile the following code?

template<class T>
struct Container
{
T x;
typedef int size_type;
size_type size() const;
};

template<class T>
Container<T>::size_type Container<T>::size() { return sizeof T; }
 
I

Ian Collins

Dmytro said:
Hi!

This code is ok:

template<class T>
struct Container
{
T x;
typedef int size_type;
size_type size() { return sizeof T; }
};

Why the compiler (VC7) does not compile the following code?

template<class T>
struct Container
{
T x;
typedef int size_type;

Why use int for a size_type? Does a negative size make sense?
size_type size() const;
};

template<class T>
Container<T>::size_type Container<T>::size() { return sizeof T; }
You left out two important things:

typename Container<T>::size_type Container<T>::size() const {
return sizeof T; }

The typename is required to tell the compiler that
Container<T>::size_type is a type and the const because the prototype
function is const.
 
J

Jakob Bieling

Dmytro said:
Why the compiler (VC7) does not compile the following code?

template<class T>
struct Container
{
T x;
typedef int size_type;
size_type size() const;
};

template<class T>
Container<T>::size_type Container<T>::size() { return sizeof T; }

Where (which line in the above snippet) and which error do you get?
My guess is you're missing a 'typename' in the last line.

hth
 
R

Rolf Magnus

Ian said:
Why use int for a size_type? Does a negative size make sense?

Actually, it does. If you want to be able to get an offset between two
arbitrary elements, that offset must be a signed type and will only be able
to span half of the range of the unsigned size type. So the size couldn't
be more anyway. And then, it's always a bad idea to mix signed and
unsigned, so actually, I would prefer a signed size type.
 
F

Frederick Gotham

Rolf Magnus posted:
And then, it's always a bad idea to mix
signed and unsigned, so actually, I would prefer a signed size type.


Some people simply used "signed int" all the time. The situation is very
similar to how some people will always use "i++" and have no intention of
changing their style.

I myself only use signed integer types when I have to. Elsewhere, I use
unsigned integer types.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top