Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to typedef on every Header file?

Tags:

c++

oop

typedef

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?

like image 827
alxcyl Avatar asked Jan 18 '13 07:01

alxcyl


1 Answers

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
like image 110
juanchopanza Avatar answered Sep 27 '22 16:09

juanchopanza