Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a class in a namespace with the same name?

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.

like image 679
Steven Avatar asked Oct 08 '09 17:10

Steven


People also ask

Can namespace and class have same name C++?

Well, a class name can be the same, but only when defined in different namespace.

Can a namespace can hold more than one class?

You can have a class in 1 to many files (if you use the "partial" keyword). You can have many classes in a namespace.

Do partial classes have to be in same namespace?

All parts of a partial class should be in the same namespace. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project.

Can a namespace inherit?

2 Answers. Show activity on this post. yes you can inheritance and namespaces are completely separate concepts. Inheritance lets you derive a child class from any none sealed object.


2 Answers

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();
}
like image 198
Steve Jessop Avatar answered Oct 24 '22 09:10

Steve Jessop


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();
}
like image 24
Khaled Alshaya Avatar answered Oct 24 '22 07:10

Khaled Alshaya