开发者

Struct vs namespace for C++ component based design

We have a component based C++ design, where each component is comprised of a public outer class that is used to group component interfaces. Each interface is defined as a nested class as shown below.

struct ComponentContainer {

    class InterfaceClass_1 : public ComponentInterface {
        public:
        virtual ~InterfaceClass_1 ()              = 0;
        virtual InterfaceClass_1* GetInterface()  = 0;
        virtual void InterfaceMethod1 ()          = 0;
        virtual void InterfaceMethod2 ()          = 0;
    };

    class InterfaceClass_2 : public ComponentInterface {
        public:
        virtu开发者_运维技巧al ~InterfaceClass_2 ()             = 0;
        virtual InterfaceClass_2* GetInterface() = 0;
        virtual void InterfaceMethod1 ()         = 0;
        virtual void InterfaceMethod2 ()         = 0;
    };
};

My first question is whether or not it is correct / advised to use a class as the container for a component? Is it more correct to replace "struct ComponentContainer" with "namespace ComponentContainer"?

Since Interface classes are always public, I have been thinking of changing the structure to look like this:

namespace ComponentContainer {

    struct InterfaceClass_1 : ComponentInterface {
        virtual ~InterfaceClass_1 ()              = 0;
        virtual InterfaceClass_1* GetInterface()  = 0;
        virtual void InterfaceMethod1 ()          = 0;
        virtual void InterfaceMethod2 ()          = 0;
    };

    struct InterfaceClass_2 : ComponentInterface {
        virtual ~InterfaceClass_2 ()             = 0;
        virtual InterfaceClass_2* GetInterface() = 0;
        virtual void InterfaceMethod1 ()         = 0;
        virtual void InterfaceMethod2 ()         = 0;
    };
};

Is this method of defining a component preferable to my first example? Are there any fundamental flaws that I need to look out for?

Thanks.


The main differences between the struct and namespace methods:

  • The struct method will require all of the interface classes contained to be declared in the same file. The namespace can be added to in multiple files. In other words: you can have several files extending the namespace ComponentContainer, which you cannot do with the struct
  • Someone may try to instantiate the wrapping struct and do things with it. Someone may even be tempted to add functionality to the wrapping struct
  • You can have "using" statements on the namespace - I'm not sure if that will actually work for the struct.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜