![](/img/trans.png)
[英]Template definition with template template parameter for class that can specialize, for instance, to std::vector<std::string> or std::map<std::tree>
[英]Container template parameter std::map or std::vector
在我的一个项目中,我使用树实现,其中使用容器C=std::map<K,V>
维护每个树节点的子代列表。 每个树节点都有一个唯一的名称密钥K
,通常为std::string
。
template<typename V, template<typename Key=std::string,typename Type=TreeNode<V>,typename ...> typename C>
class TreeNode {
typedef C<std::string, Value> cont_type;
typedef V data_type;
cont_type childs;
data_type value;
cont_type::iterator genericFind(const K& k) {
// Something generic here!!!
}
}
除了以下事实外,该实现对我来说还算不错,即std :: map不遵守在树中插入的顺序。 对于某些应用程序,我需要保持插入顺序,但是对于其他应用程序,需要快速信息重发更为重要。
因此, C
必须是任何一种类型
std::vector<std::pair<K, V>> // keeping insertion order
要么
std::map<K,V> // fast information retrivial
不,我的TreeNode
类的实现存在问题,仍然显式使用std::map
的接口。 特别是,它使用成员函数find
, erase
和insert
,这些成员函数需要用通用的东西替换,其中两种容器类型的实现都非常具体。
例如childs.find(key)
需要被替换为find(childs.begin(), childs.end(), key)
,每当我插件std::vector
实现。
也许还有另一种我不知道的解决方案。 这可能是boost::multi_index
,但是我对此不太确定。
解决我的问题的最简单方法是什么?
您可以创建专用的重载函数并使用它们
template <typename Key, typename V>
auto my_find(std::map<Key, V>& m, const Key& key)
{
return m.find(key);
}
template <typename Key, typename V>
auto my_find(std::vector<std::pair<Key, V>>& v, const Key& key)
{
return std::find_if(v.begin(), v.end(), [&](const auto& p) {
return p.first == key;
});
}
使用相同的界面为所需的容器“选择”创建通用包装:
template <typename TKey, typename TValue>
class my_map_wrapper
{
private:
std::map<TKey, TValue> _map;
public:
// Same interface as 'my_vector_wrapper'.
template <typename TEKey, typename TEValue>
void emplace(TEKey&& key, TEValue&& value)
{
_map.emplace(std::make_pair(std::forward<TEKey>(key),
std::forward<TEValue>(value)));
}
// ...
};
template <typename TKey, typename TValue>
class my_vector_wrapper
{
private:
std::vector<std::pair<TKey, TValue>> _vec;
public:
// Same interface as 'my_map_wrapper'.
template <typename TEKey, typename TEValue>
void emplace(TEKey&& key, TEValue&& value)
{
_vec.emplace_back(std::forward<TEKey>(key),
std::forward<TEValue>(value));
}
// ...
};
在包装器本身上对树节点类进行模板化:
template <typename TWrapper>
class TreeNode
{
private:
TWrapper _container;
public:
// Use "uniform" container interface...
};
现在,您可以定义方便的类型别名,以在用户代码中的容器之间进行选择:
template <typename TKey, typename TValue>
using MapTreeNode = TreeNode<my_map_wrapper<TKey, TValue>>;
template <typename TKey, typename TValue>
using VectorTreeNode = TreeNode<my_vector_wrapper<TKey, TValue>>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.