【问题标题】:Cryptic template template parameter error神秘的模板模板参数错误
【发布时间】:2013-08-13 23:06:50
【问题描述】:

我正在尝试创建一个从std::mapstd::unordered_map 获取密钥的函数。我可以使用简单的重载,但首先我很想知道这段代码有什么问题。

template<typename K, typename V, template<typename, typename> class TContainer>  
std::vector<K> getKeys(const TContainer<K, V>& mMap)
{
    std::vector<K> result;
    for(const auto& itr(std::begin(mMap)); itr != std::end(mMap); ++itr) result.push_back(itr->first);
    return result;
}

当使用 std::unordered_map 调用它时,即使手动指定 all 模板类型名,clang++ 3.4 会说:

模板模板参数的模板参数与其对应的模板模板参数不同。

【问题讨论】:

    标签: c++ templates c++11 types typename


    【解决方案1】:

    问题在于std::mapstd::unordered_map 实际上并不是带有两个参数的模板。它们是:

    namespace std {
        template <class Key, class T, class Compare = less<Key>,
                  class Allocator = allocator<pair<const Key, T>>>
        class map;
    
        template <class Key, class T, class Hash = hash<Key>,
                  class Pred = equal_to<Key>,
                  class Allocator = allocator<pair<const Key, T>>>
        class unordered_map;
    }
    

    这里有类似的方法:

    template <typename K, typename... TArgs, template<typename...> class TContainer>
    std::vector<K> getKeys(const TContainer<K, TArgs...>& mMap)
    {
        std::vector<K> result;
        for (auto&& p : mMap)
            result.push_back(p.first);
        return result;
    }
    

    我更喜欢的版本:

    template <typename Container>
    auto getKeys2(const Container& mMap) -> std::vector<typename Container::key_type>
    {
        std::vector<typename Container::key_type> result;
        for (auto&& p : mMap)
            result.push_back(p.first);
        return result;
    }
    

    使用这两个函数的演示程序:http://ideone.com/PCkcu6

    【讨论】:

    • 哦,我现在觉得自己好傻。有没有办法同时匹配mapunordered_map 而不会创建两个不同的重载?模板参数的数量不同。
    • 编辑了可能的“修复”。但以某种方式使用decltype(mMap)::key_type 可能会更好。
    • 在发布前几分钟想出了相同的修复方法,呵呵。谢谢你的一切!
    • 在我看来有很大的进步。我将auto 更改为const auto&amp; 并在我的库中实现了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2020-10-13
    • 2011-07-14
    相关资源
    最近更新 更多