egcs-1.0.2 STL problem?

Ross Smith ross.smith@nz.eds.com
Wed Mar 25 14:00:00 GMT 1998


Pinwu Xu wrote:
> 
> Hi there,
>    I've been having problem with the following code section:
> 
> #include<proper head>
> 
> main()
> {
>     vector<int> a_i_vec(5, 0);
>     ....
> }
> 
> if I change the main() code to
>     int dummy_int(0);
>     vector<int> a_i_vec(5, dummy_int);
> 
> it works. You can find the examples for the former code in
> several books for STL. It would be appreciated if somebody
> could shed a light.

This is a problem intrinsic to the way the STL works, not an EGCS bug.
Containers of integer types require careful casting to make some of the
constructors work properly. Two of the constructors of any sequential
container look like this:

    container<T>(container<T>::size_type n, const T& value);
    template <class InputIterator> container<T>(InputIterator first,
InputIterator last);

The size_type of a container is normally unsigned int, and its iterator
type is int*, so for a vector<int>, the first constructor wants
(unsigned, int), while the second will be happy with any two types that
can be used as iterators, including int*. So the constructor signatures
look like:

    vector<int>(unsigned, int)
    vector<int>(int*, int*) // or other specialisations

The rules of C++ say that a plain 0 can be read as either the integer
zero or a null pointer. So your first attempt can look like either
vector<int>(int, int) or vector<int>(int, int*) to the compiler. It will
happily convert this to either of the two signatures above, so you get
an ambiguity error.

You second attempt uses an integer variable rather than the constant 0,
so it can only be read as vector<int>(int, int). This converts more
easily to the first signature, so the ambiguity goes away.

You should be able to make the first version work by explicitly casting
the first argument to the right type:

    vector<int> a_i_vec(vector<int>::size_type(5), 0);

(Why not the second? Because any constant integer expression with value
0 can be read as a null pointer, so int(0) is still ambiguous. Annoying
but we're stuck with it.)

-- 
Ross Smith ............................. < mailto:ross.smith@nz.eds.com >
Internet and New Media, EDS (New Zealand) Ltd., Wellington, New Zealand
"Isn't it interesting that the same people who laugh at science fiction
listen to weather forecasts and economists?" -- Kelvin Throop III



More information about the Gcc mailing list