类模板,函数成员定义

时间:2013-02-14 14:17:49

标签: c++ templates

我正在学习如何使用类模板。我已经阅读了很多例子,但我仍有一些问题。

我的标题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;
}

以下是编译错误(Kdevelop中的g ++)

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类型?

如果我不保存std::pair返回的insert(),编译工作正常。

2 个答案:

答案 0 :(得分:3)

在这种情况下,iterator是一个从属名称,您应该使用typename关键字对其进行限定:

 pair<typename map<string, T>::iterator, bool>

有关详细信息,请参阅this question

答案 1 :(得分:1)

尝试编写对&lt; typename map :: iterator。迭代器是一种取决于模板参数的类型,编译器需要一些帮助来识别它。