模板类困境;适当的模板签名?

时间:2013-04-08 23:17:56

标签: c++ templates

我正在实现一个模板类,我不确定我的签名是否正确。下面我列出了我的代码示例,显示了我担心的几种情况:

mymap.h:


#ifndef MAP_H
#define MAP_H
#include <iostream>
#include <string>

using namespace std;

template <typename KEY, typename T>
class Map{
private:
    struct Elem {

    };

public:

    Map();
    // constructs empty Map

    Map(const Map &rhs);

    ~Map();

    Map& operator=(const Map &rhs);

    bool insert(KEY, T);

    T& operator[](KEY);

};

template<typename KEY, typename T>
ostream& operator<< (ostream&, const Map<KEY, T>&);

#include "mymap.cpp"

#endif

现在是.cpp文件:


#include mymap.h
#include <iostream>
#include <string>

using namespace std;

//Assingment Operator
template < typename KEY , typename T >
Map< KEY , T >& Map< KEY , T >::operator=(const Map &rhs){

    //Avoid self assignment
    if( this != &rhs ){

         //Snip
    }

    return *this;
}


//Insert, return true if successful.
template < typename KEY , typename T >
bool Map< KEY , T >::insert(KEY, T){

    //Snip
}

正如你所看到的,我相信你们都很清楚,模板签名可能会因我读到的内容而变得非常混乱。这看起来是否正确,或者我是否有一些容易被更熟练的眼睛注意到的致盲错误?

我知道有一百万个关于模板的帖子,我已经阅读了一些关于它们的指南,但我仍然无法在这个具体问题上找到太多。

此外,在不可避免的“摆脱使用命名空间std”注释出现之前,我将其包含在调试中, 最终会消失,我保证:)

谢谢!


编辑:对于这种混乱感到抱歉,我似乎错过了我发布的一个非常重要的部分...错误!

我有大约5个,都有不同的行号:

mymap.cpp:41:1: error: ‘Map’ does not name a type

和相同数量的:

expected initializer before ‘<’ token

1 个答案:

答案 0 :(得分:2)

#include mymap.h

中删除mymap.cpp

然后

#include "mymap.h"
test.cpp

中的

并使用

进行编译
g++ -g test.cpp

对于模板类,所有内容都必须在标题中。