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?
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.
+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() { }
};
LIVE EXAMPLE
Or use C++11's inherited constructors feature:
struct AnotherException : public exception::MyException
{
using MyException::MyException;
};
LIVE EXAMPLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With