1

I've been new to C++, and is now going through templates and have encountered this question.

When the template type requires another class, will there be a specific requirement of the header include order?

vector<string> stringVector;

Like this: should we include string prior to vector?

I read this (C++ Header order) and it's saying that the header files should be included in the class-requirement order.

However, as this (Template Compilation) indicates, or if it is my misunderstanding, "the compiler generates the code for the specific types given in the template class instantiation", and I think this means that when we are instantiating the stringVector, the compiler already included string header, so there should not be a "vector here is string required" relationship.

So, which interpretation is right, and which part of my interpretation is right or wrong? Thanks.

Community
  • 1
  • 1
Haotian Liu
  • 886
  • 5
  • 19

2 Answers2

3

Whenever you use a template in c++, the used template type has to be known as a complete type, that requires you to include the string class when you want to use a vector of string. The includes are nothing more than copying and pasting the code in the included file to where your include is placed.

1> #include <string>
2> #include <vector>
3>  
4> class Foo {
5> private:
6>     vector<string> bar;    
7> }

When the line 6 is compiled, the compiler has to know both types as complete type (string because its a template, vector because its not a pointer). The includes are placed over the class so the compiler knows both types when he wants to compile line 6. It doesn't matter which order you included them.

Janis
  • 1,020
  • 6
  • 14
2

You basically have to include all the dependecies before using them. So it does not matter in your example, if string or vector is included first. They just have to be included both before using them.

The order does matter if the header files are dependend from each other. Lets say there is a header file a.h and b.h, where b.h is dependend from a.h. THEN a.h has to be included first. But if someone has to do it that way, the program is not written in a clean way. All dependecies of a header file should be included in a header file using include guards and not somewhere else.

This is as far as i understand it.

Aeonos
  • 365
  • 1
  • 13
  • 1
    thanks for the completion :) Important thing is: "if someone has to do it that way, the program is not written in a clean way." – Janis Feb 02 '17 at 12:24