Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

namespace called 'exception' leads to compile problems

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?

like image 445
meddle0106 Avatar asked Mar 25 '14 07:03

meddle0106


2 Answers

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.

like image 87
Mike Seymour Avatar answered Sep 18 '22 22:09

Mike Seymour


+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

like image 33
Mark Garcia Avatar answered Sep 20 '22 22:09

Mark Garcia