Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ defining a static member of a template class with type inner class pointer

I have a template class like here (in a header) with a inner class and a static member of type pointer to inner class

template <class t> class outer {
    class inner {
        int a;
    };

    static inner *m;
};

template <class t> outer <t>::inner *outer <t>::m;

when i want to define that static member i says "error: expected constructor, destructor, or type conversion before '*' token" on the last line (mingw32-g++ 3.4.5)

like image 595
Jack Avatar asked Oct 22 '25 11:10

Jack


1 Answers

You need to qualify that the inner class is a typename, since it’s dependent on a template parameter and the C++ compiler assumes that the name inner in this context is not a type:

template <class t> typename outer<t>::inner* outer<t>::m;

Rationale: the name inner in the above line depends on a type name, t. The C++ compiler at this point doesn’t know what inner is, because the meaning of the name inner can differ depending on t. For example, suppose that, somewhere else in the code, there is a specialized version of the outer class for int:

template <>
class outer<int> {
    int inner;
};

Now, outer<int>::inner no longer names a type; it names a member variable.

Thus, in the general case the meaning of outer<t>::inner would be ambiguous and C++ resolves this ambiguity assuming that inner does not name a type. Unless you say it does, by prefixing it with typename: typename outer<t>::inner. (In this context, inner is called a dependent name since it depends on the exact type of t.)

like image 66
Konrad Rudolph Avatar answered Oct 24 '25 19:10

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!