Nested class definition outside outer class's, while outer class contains instance of inner class

喜夏-厌秋 提交于 2019-12-05 16:30:29

This is a red flag, but you can do it using a fake template.

template< typename = void >
struct Outer_temp
{
    struct Inner;
    Inner myinner;
    Outer_temp() : myinner(2) {}
};

typedef Outer_temp<> Outer; // Hide template from user.

template< typename v >
struct Outer_temp< v >::Inner
{
    Inner(int n) : num(n) {}
    int num;
};

int main()
{
    Outer myouter;
}

Inner inside the template is a dependent type, so it does not need to be complete as you define an instance, in a member or any other context. It only needs to be complete once the instantiation happens, in this case from main.

I can't imagine a good reason to do this, but there it is.

Nested classes should not be used for the sake of program organization. Nesting suggests a conceptual dependency, "Inner cannot exist except in a context provided by Outer." Although it is common, for example, for a container node class to be nested within the container, this can cause problems. The SCARY idiom is a design style that repudiates such organization and gains improved genericity.

TL;DR: define the two classes independently and link them with a nested typedef.

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