Reputation: 1292
I have a problem with a namespace called "exception"
Let's consider following example header:
#include <exception>
namespace exception
{
struct MyException : public std::exception
{};
}
struct AnotherException : public exception::MyException
{
AnotherException() : exception::MyException() { }
};
This header does not compile with following error:
namespacetest.hpp: In constructor 'AnotherException::AnotherException()': namespacetest.hpp:12:48: error: expected class-name before '(' token namespacetest.hpp:12:48: error: expected '{' before '(' token
There are two solutions for this:
1) qualify namespace with "::" in line 12
AnotherException() : ::exception::MyException() { }
2) Rename namespace to e.g. "exceptional"
What is the reason, that the namespace "exceptions" leads to confusion? I know that there is a class std::exception. Does this cause the trouble?
Upvotes: 17
Views: 859
Reputation: 17708
+1 to @Mike Seymour's answer! As a supplement, there are better ways than your current solution to prevent the ambiguity:
Just use MyException
, without any namespace qualification:
struct AnotherException : public exception::MyException
{
AnotherException() : MyException() { }
};
Or use C++11's inherited constructors feature:
struct AnotherException : public exception::MyException
{
using MyException::MyException;
};
Upvotes: 10
Reputation: 254691
I know that there is a class
std::exception
. Does this cause the trouble?
Yes. Within std::exception
, the unqualified name exception
is the injected class name. This is inherited so, within your class, an unqualified exception
refers to that, not your namespace.
Upvotes: 22