Initializing static const variables of template classes

Discussion in 'C++' started by david.baird, Mar 17, 2007.

  1. david.baird

    david.baird Guest

    I have 3 classes, 1 which does not use templates, CGood, and 2 which
    do use templates, CBad, and COkay. I believe that all of them should
    work, but only CGood and COkay are working for me. CBad fails to
    compile.

    class CGood
    {
    public:
    typedef int arr_t[2];
    static const arr_t bar;
    };

    const CGood::arr_t CGood::bar = { 1, 2 };

    template <class T>
    class CBad
    {
    public:
    typedef T arr_t[2];
    static const arr_t bar;
    };

    template <class T>
    // g++ says ``error: expected initializer before 'CBad''':
    const CBad<T>::arr_t CBad<T>::bar = { 1, 2 };

    template <class T>
    class COkay
    {
    public:
    typedef T arr_t[2];
    static const arr_t bar;
    };

    template <class T>
    const T COkay<T>::bar[2] = { 1, 2 };

    Can anyone tell me if there is something is wrong (or right) with
    CBad? It seems fine to me, but the compiler just doesn't like it.

    If it is helpful, here is my g++ version:

    $ g++ --version
    g++ (GCC) 4.1.1 (Gentoo 4.1.1-r3)
     
    david.baird, Mar 17, 2007
    #1
    1. Advertisements

  2. david.baird

    david.baird Guest

    Well, I just figured it out :) Maybe someone will find this
    useful...

    On Mar 17, 1:17 am, "david.baird" <> wrote:
    > template <class T>
    > // g++ says ``error: expected initializer before 'CBad''':
    > const CBad<T>::arr_t CBad<T>::bar = { 1, 2 };


    Instead, use the typename keyword:

    template <class T>
    const typename CBad<T>::arr_t CBad<T>::bar = { 1, 2 };


    This website says some nice things about typename (though I am still
    trying to wrap my head around it):

    http://www.gotw.ca/gotw/035.htm
    GotW #35
     
    david.baird, Mar 17, 2007
    #2
    1. Advertisements

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. Steven T. Hatton
    Replies:
    1
    Views:
    7,009
    Siemel Naran
    Apr 19, 2004
  2. Steven T. Hatton

    static const members of template classes?

    Steven T. Hatton, Oct 1, 2004, in forum: C++
    Replies:
    3
    Views:
    3,801
    John Harrison
    Oct 1, 2004
  3. Rakesh Sinha
    Replies:
    4
    Views:
    2,141
    Rakesh Sinha
    Jan 13, 2005
  4. Dave
    Replies:
    10
    Views:
    35,825
    Ron Natalie
    May 22, 2005
  5. Drew McCormack
    Replies:
    2
    Views:
    930
    Drew McCormack
    Jun 24, 2005
  6. Marc D
    Replies:
    2
    Views:
    504
    Marc D
    Feb 14, 2007
  7. Javier
    Replies:
    2
    Views:
    892
    James Kanze
    Sep 4, 2007
  8. er
    Replies:
    3
    Views:
    488
Loading...