C++ – Forward declaration and alias (with using or typedef)


I need to implement the following interface

struct mutex;
struct interface
  mutex& getMutex();

Intuition would I could use using mutex = ParticularMutex in my implementation, but gcc tells me otherwise:

error: conflicting declaration ‘using mutex = ’
error: ‘class mutex’ has a previous declaration as ‘class mutex’

I am not defining anything twice, only declaring twice, as usual when forward declaring, so

  1. why doesn’t this work?
  2. is there a workaround without modifying interface?
  3. how should interface have been defined? with template <typename mutex>?


  1. It does not work because the forward declaration struct mutex; tells the compiler that mutex is a new type. With using you are then creating a type alias, which means it’s not a new type (as promised to the compiler), but an alias to an existing type.

  2. No.

  3. Yes.

What you could do is:

struct mutex : ParticularMutex {
    using ParticularMutex::ParticularMutex; // inherit constructors

Which does define a type derived from ParticularMutex which is hopefully compatible enough. Of course, this is a new type which might lead to other problems.

Answered By – Daniel Frey

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.