Home > Mobile >  How do I do a forward declaration of a struct with a typename?
How do I do a forward declaration of a struct with a typename?

Time:02-13

I am trying to do a forward declaration of a struct in c that has a typename. Something like this is entirely valid:

typedef struct foo foo;

struct foo{
    int f;
};

My struct just instead has a typename, so I tried this:

template <typename T>
typedef struct mV<T> mV;

template <typename T>
struct mV{
   //contents of struct
};

However, I then get the errors a typedef cannot be a template, explicit specialization of undeclared template struct and redefinition of 'mV' as different kind of symbol. How can I go about fixing that?

CodePudding user response:

You're describing a forward- declaration . (A future is something completely different in modern C ).

typedef aliasing structure tags is not needed, and rarely desired, in C . Instead you simply declare the class type and be done with it.

// typedef struct mV mV;  // not this
struct mV;                // instead this

The same goes for templates

template<class T>
struct mV;

If you need/want to attach an alias to your template type, you still can do so via using

template<class T>
struct mV;

template<class T>
using MyAliasNameHere = mV<T>;

Armed with all of that, and heading off what I surmise you'll be discovering in short order, you'll probably need to read this as well: Why can templates only be implemented in header files?. Something tells me that's about to become highly relevant.

  • Related