我想实现一个包含字典等的类。有一个简化的示例,其中我使用地图来实现它:
#include <map>
#include <iostream>
class Position {
public:
typedef std::string AttrKey;
typedef std::string AttrValue;
typedef std::map<AttrKey, AttrValue> AttrMap;
Position() = default;
void set(const AttrKey& key, const AttrValue& value)
{
attrs[key] = value;
}
AttrValue get(const AttrKey& key) const
{
const auto found = attrs.find(key);
if (found != attrs.end())
return found->second;
return "";
}
const AttrMap& getAttrs() const
{
return attrs;
}
private:
AttrMap attrs;
};
int main()
{
Position p;
p.set("some_key", "some_value");
std::cout << "This is the value: "<< p.get("some_key");
return 0;
}
现在,我想动态地决定值的类型,以便字典不仅包含字符串值。我是pythonist,所以对自己的工作了解很少。但是,我尝试制作一个Foo
模板类,以便将任何值放入其中并将其作为AttrValue
的别名(,而且我也不想使用Boost ):
#include <map>
#include <iostream>
template <class T>
class Foo
{
public:
typedef T Bar;
};
class Position {
public:
template <typename T>
using Bar = typename Foo<T>::Bar;
typedef std::string AttrKey;
typedef Bar AttrValue;
typedef std::map<AttrKey, AttrValue> AttrMap;
Position() = default;
void set(const AttrKey& key, const AttrValue& value)
{
attrs[key] = value;
}
AttrValue get(const AttrKey& key) const
{
const auto found = attrs.find(key);
if (found != attrs.end())
return found->second;
return "";
}
const AttrMap& getAttrs() const
{
return attrs;
}
private:
AttrMap attrs;
};
int main()
{
Position p;
p.set("some_key", 42);
std::cout << "This is the Answer to the Ultimate Question of Life, The Universe, and Everything: "<< p.get("some_key");
return 0;
}
我在这里遇到错误invalid use of template-name ‘Position::Bar’ without an argument list
。