简体   繁体   中英

Can a namespace be used as an Object Template in C++?

I know in c++, struct can be used as an object template, and I know that class can be used as an object template.

Can namespace be used as an Object Template ?

To be clear;

MyClass myclass;
myclass.memberFunction();
MyStruct mystruct;
mystruct.memberFunction();

Can you do something along the lines of:

MyNamespace mynamespace;
mynamespace.MyClass.memberFunction();

Either by that syntax, or something similar.

By definition, namespace is just a namespace, it's not template or factory of anything, the closest counterpart in Java is package, so if you're thinking of creating a new instance of a namespace, it not possible and meaningless, just like you cannot create instance of package in Java.

But if you just want to give an existing namespace an alias, you can so something like:

namespace MyNamespace {
    class MyClass {
    public:
        static void MyStaticFunction(...) {...}
    };
}

namespace mynamespace=MyNamespace;
mynamespace::MyClass::MyStaticFunction(...);

Note that only static member functions can be called without a class instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM