I'm learning how to use class templates. I have read a number of examples, but I still have some problems.
I have the following template class in my header 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;
};
This is the implementation file 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;
}
The followings are the compilation errors (g++ within 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’
So it looks like std::pair
cannot deal with T
type?
If I don't save the std::pair
returned by insert()
, compilation works fine.