为什么在模板头的末尾添加.cpp不是循环依赖

Why it is not circular dependency to add .cpp at end of template header?

本文关键字:cpp 添加 依赖 循环 为什么      更新时间:2023-10-16

我不敢问为什么我需要在模板声明时在.h的末尾添加.cpp。因为它已经在StackOverflow中被回答过很多次了。

但我的问题是,为什么它不是循环依赖,或者编译器如何不继续添加.cpp.h.h.cpp,当我添加。cpp在头结束?

c++ 11试图解决这个奇怪的模板需求吗?

@Edit:只包括头文件

#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

谢谢。

撇开这种技术的优点不谈,您的问题中的代码之所以有效,是因为包含保护:

#ifndef MYMAP
#define MYMAP
...
#endif

第二次包含.h时,它实际上是一个no-op,因为MYMAP在第一次循环中已经定义了。

注:不要在头文件中执行using namespace std。任何包含此标题的代码都将把整个std名称空间带入当前作用域,无论他们是否想要它