クラステンプレートの使い方を学んでいます。いくつかの例を読みましたが、まだいくつか問題があります。
ヘッダーに次のテンプレートクラスがあります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()
、コンパイルは正常に機能します。