Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>?
like image 618
ricab Avatar asked Sep 16 '13 18:09

ricab


People also ask

Should I use typedef or using?

One can declare the same variable using typedef in 2 or more different files and no error will be thrown till both refer to the same type. In C++, 'typedef' allows the programmer to declare multiple types at once, unlike the 'using' statement.

Can you forward declare in C?

In Objective-C, classes and protocols can be forward-declared like this: @class MyClass; @protocol MyProtocol; In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. MyClass * or id<MyProtocol>.

Why should I use forward declarations?

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.

Can you forward declare a typedef C++?

But you can't forward declare a typedef.


1 Answers

  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.

like image 190
Daniel Frey Avatar answered Oct 25 '22 23:10

Daniel Frey