我正在学习如何使用类模板。我已经阅读了一些例子,但我仍然有一些问题。类模板,函数成员定义
我有我的头foo.h
下面的模板类:
template<typename T>
class Foo
{
public:
bool addKey(const std::string& key);
bool addValue(const std::string& key, const T& value);
private:
std::map<std::string, T> mapping;
};
这是实现文件foo.cpp
:
template <typename T>
bool Foo<T>::addKey(const string& key)
{
if (key.empty())
return false;
pair<map<string, T>::iterator, bool> response; // to store the pair returned by insert()
response = mapping.insert(pair<string, T>(key, T()));
return response.second;
}
以下是编译错误(G ++中的KDevelop)
error: type/value mismatch at argument 1 in template parameter list for ‘template<class _T1, class _T2> struct std::pair’
error: expected a type, got ‘std::map<std::basic_string<char>, T>::iterator’
error: invalid type in declaration before ‘;’ token
error: request for member ‘second’ in ‘response’, which is of non-class type ‘int’
所以看起来像std::pair
不能处理T
类型?
如果我不保存由insert()
返回的std::pair
,则编译工作正常。
您不能将类模板的成员函数的定义放在'.cpp'文件中 – 2013-02-14 14:19:34
看看http://stackoverflow.com/questions/610245/where-and-why-do-i-have- to-put-the-template-and-typename-keywords – JoergB 2013-02-14 14:21:25
在C++中没有“模板类”这样的事情。他们是“类模板” - 从字面上看,用于制作类的模板和* not *“模板化的类”。这是一个小而重要的区别,在实例化模板时很重要。 – 2013-02-14 14:21:29