alxcyl
alxcyl

Reputation: 2722

Do I have to typedef on every Header file?

Let's say I have an std::vector of std::strings.

// Foo.h
class Foo {
    std::vector< std::string > mVectorOfFiles;
}

Then I used typedef to make it a StringVector type.

// Foo.h
typedef std::vector< std::string > StringVector;

class Foo {
    StringVector mVectorOfFiles;
}

If I have another class which takes a StringVector object...

// Bar.h
class Bar {
    Bar( const StringVector & pVectorOfFiles ); // I assume this produces a compile error (?) since Bar has no idea what a StringVector is
}

... do I have to use typedef again in the header file for Bar?

// Bar.h
typedef std::string< std::vector > StringVector;
class Bar {
    Bar( StringVector pListOfFiles );
}

Is it possible to place the typedef std::vector< std::string > StringVector in a single file and have every other class know of the type StringVector?

Upvotes: 9

Views: 11772

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24153

Create a class instead.

class Files {
};

Then you can use a forward declaration wherever it's needed;

class Files;

You will encapsulate behaviour appropriate to files.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227468

All files that #include "Foo.h" you get the typedef. So no, you don't have to replicate it in every file (as long as it includes Foo.h. You can place the typedef in a dedicated file if that suits your needs. In your case, this would make sense and would be an improvement, because Bar.h should not rely on the fact that Foo.h has the typedef and the necessary includes.

I would keep it simple and limit it to one type though, to be included in all files that use the type:

// StringVector.h
#ifndef STRINGVECTOR_H_
#define STRINGVECTOR_H_

#include <vector>
#include <string>

typedef std::vector< std::string > StringVector;

#endif

Upvotes: 20

Didac Perez Parera
Didac Perez Parera

Reputation: 3834

Of course not, you do not have to typedef in all the header files, just do it in any header file that is included by the rest of source files.

Upvotes: 0

Related Questions