Template problem

Discussion in 'C++' started by Vespasian, May 23, 2004.

  1. Vespasian

    Vespasian Guest

    I get the following compilation errors,

    error C2057: expected constant expression
    error C2133: 'tempArray' : unknown size
    error C2466: cannot allocate an array of constant size 0

    when compiling the following code:

    template<class X> class Array {
    public:
    Array(int s) {size = s; }
    int get_size(void) { return size; }
    private:
    int size;
    };

    #include <iostream>
    #include <string>
    #include "temp.h"
    using namespace std;

    template<class X> void Merge (Array<X>& values)
    {
    X tempArray[values.get_size()];
    }

    int main() {
    int num;
    cout << "How many words? ";
    cin >> num;
    Array<string> b(num);

    Merge(b);

    return 0;
    }


    Not sure why the errors occur. How do I fix this problem?

    TIA,
    ves
    Vespasian, May 23, 2004
    #1
    1. Advertising

  2. Vespasian wrote:

    > template<class X> void Merge (Array<X>& values)
    > {
    > X tempArray[values.get_size()];
    > }



    You can't do that in standard C++. The dimension of the array must be a
    constante evaluable at compile time. Use a vector instead, for example.

    --
    Salu2
    =?ISO-8859-15?Q?Juli=E1n?= Albo, May 23, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris Theis
    Replies:
    2
    Views:
    453
    Chris Theis
    Jul 24, 2003
  2. tom_usenet
    Replies:
    0
    Views:
    520
    tom_usenet
    Jul 24, 2003
  3. Replies:
    1
    Views:
    2,082
    Gianni Mariani
    Jun 8, 2007
  4. Peng Yu
    Replies:
    3
    Views:
    754
    Thomas J. Gritzan
    Oct 26, 2008
  5. nguillot
    Replies:
    5
    Views:
    514
Loading...

Share This Page