加密模板模板参数错误 [英] Cryptic template template parameter error

查看:253
本文介绍了加密模板模板参数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a function that gets the keys from a std::map or an std::unordered_map. I could use a simple overload, but first I'd love to know what's wrong with this code.

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也会说:

When calling it with an std::unordered_map, even specifying all template typenames manually, clang++ 3.4 says:

模板模板参数与相应的模板模板参数具有不同的模板参数.

template template argument has different template parameters than its corresponding template template parameter.

推荐答案

问题是std::mapstd::unordered_map实际上不是带有两个参数的模板.他们是:

The problem is that std::map and std::unordered_map are not in fact templates with two parameters. They are:

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;
}

这里有一些类似的方法可以工作:

Here's something similar that does work:

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

A demo program using both functions: http://ideone.com/PCkcu6

这篇关于加密模板模板参数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆