Using a class in a namespace with the same name?

こ雲淡風輕ζ 提交于 2019-12-04 02:56:15

问题


I have to use an API provided by a DLL with a header like this

namespace ALongNameToType {
    class ALongNameToType {
        static void Foo();   
    }
}

Is there a way to use ALongNameToType::ALongNameToType::Foo without having to type ALongNameToType::ALongNameToType each time? I tried using using namespace ALongNameToType but got ambiguous symbol errors in Visual Studio. Changing the namespace name or removing it gives me linker errors.


回答1:


I don't know what's ambiguous, but you can avoid all conflicts with other Foo functions like this:

namespace ALongNameToType {
    struct ALongNameToType {
        static void Foo();   
    };
}

typedef ALongNameToType::ALongNameToType Shortname;

int main() {
    Shortname::Foo();
}



回答2:


namespace myns = ALongNameToType;

It seems that you can't alias a class scope like this:

// second ALongNameToType is a class
namespace myns = ALongNameToType::ALongNameToType;

Maybe you could alias the function it self:

namespace foo
{
 class foo
 {
 public:
  static void fun()
  {

  }
 };
}

int main()
{
 void (*myfunc)() = foo::foo::fun;

 myfunc();
}



回答3:


using ALongNameToType::ALongNameToType::Foo;

if you just want to use it as Foo().




回答4:


There are three ways to use using. One is for an entire namespace, one is for particular things in a namespace, and one is for a derived class saying it doesn't want to hide something declared/defined in a base class. You can use the second of those:

using ALongNameToType::ALongNameToType

Unfortunately this isn't working for you (due to the ambiguity of the namespace and the class having the same name). Combining this type of using with a previous answer should get rid of the ambiguity:

namespace alntt = ALongNameToType;
using alntt::ALongNameToType;

But once you've renamed the namespace, you really don't need the using statement (as long as you're comfortable writing the (shortened) namespace every time you use the class:

namespace alntt = ALongNameToType;
alntt::ALongNameToType a;
...


来源:https://stackoverflow.com/questions/1539333/using-a-class-in-a-namespace-with-the-same-name

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