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

徘徊边缘 提交于 2019-12-23 19:14:34

问题


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)


回答1:


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.)



来源:https://stackoverflow.com/questions/2487437/c-defining-a-static-member-of-a-template-class-with-type-inner-class-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!