Ale*_*ent 7 c++ templates overloading overload-resolution class-template
template<class Key1, class Key2, class Type> class DualMultimapCache
{
public:
std::list<std::reference_wrapper<Type>> get(Key1 const & key);
std::list<std::reference_wrapper<Type>> get(Key2 const & key);
template<class ...Args> Type & put(Key1 const & key, Args const & ...args);
template<class ...Args> Type & put(Key2 const & key, Args const & ...args);
};
Run Code Online (Sandbox Code Playgroud)
在这里,我有一个类的公共接口.基础数据结构无关紧要.一切都将只是正常工作时Key1,并Key2有不同的类型.如果它们最终成为相同的类型,则过载可能是不可能的.我这是对的吗?
如果我是,有没有办法分离过载,同时保持签名尽可能干净?
编辑:这是一个更深入的样本
template<class Key1, class Key2, class Type> class DualMultimapCache
{
public:
std::list<std::reference_wrapper<Type>> get(Key1 const & key);
std::list<std::reference_wrapper<Type>> get(Key2 const & key);
template<class ...Args> Type & put(Key1 const & key, Args const & ...args);
template<class ...Args> Type & put(Key2 const & key, Args const & ...args);
private:
std::unordered_multimap<Key1, std::reference_wrapper<Type>> map_Key1;
std::unordered_multimap<Key2, std::reference_wrapper<Type>> map_Key2;
};
template<class Key1, class Key2, class Type>
std::list<std::reference_wrapper<Type>> DualMultimapCache<Key1, Key2, Type>::get(Key1 const & key)
{
auto its = map_Key1.equal_range(key);
if (its.first == map.cend() && its.second == map.cend())
throw std::out_of_range();
else
return { its.first, its.second };
}
template<class Key1, class Key2, class Type>
std::list<std::reference_wrapper<Type>> DualMultimapCache<Key1, Key2, Type>::get(Key2 const & key)
{
auto its = map_Key2.equal_range(key);
if (its.first == map.cend() && its.second == map.cend())
throw std::out_of_range();
else
return { its.first, its.second };
}
Run Code Online (Sandbox Code Playgroud)
您可以针对相同密钥类型的情况部分专门化模板,例如
template <typename Key, typename Type>
class DualMultimapCache<Key, Key, Type>
{
public:
std::list<std::reference_wrapper<Type>> get(Key const & key);
template<class ...Args> Type & put(Key const & key, Args const & ...args);
};
Run Code Online (Sandbox Code Playgroud)