Question

I will not dare to ask why I need to add .cpp at end of .h while template declaration. Because it has been answered many times in StackOverflow.

But my question is, how come it is not circular dependency, or how compiler do not keep on adding .cpp into .h and .h into .cpp, when I add .cpp at end of header?

Does C++ 11 tries to solve this strange template requirement?

@Edit: Just including header file

#ifndef MYMAP
#define MYMAP

#include <iostream>
#include <string>

using namespace std;

template<typename ValType>
class MyMap
{
public:
    MyMap();
    ~MyMap();

    void add(string key, ValType val);
    ValType getValue(string key);

private:

    static const int NumBuckets = 99;

    struct cellT
    {
        string key;
        ValType val;
        cellT* next;
    };

    cellT *buckets[NumBuckets];

    int hash(string key, int numBuckets);

    cellT* findCellForKey(string key, cellT *head);

    MyMap(MyMap&);
    MyMap operator = (MyMap&);


};

#include "MyMap.cpp" //included .cpp

#endif

@Edit 2 : MyMap.cpp

#include "MyMap.h"

//rest of the code

Thanks.

Was it helpful?

Solution

Leaving aside the merits of this technique, the code in your question works because of the include guard:

#ifndef MYMAP
#define MYMAP
...
#endif

The second time the .h is included, it is effectively a no-op since MYMAP has been defined the first time round.

P.S. Don't do using namespace std in a header file. Any code that includes this header will have the entire std namespace brought into the current scope irrespective of whether they want it or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top