gpt4 book ai didi

c++ - Cryptic template 模板参数错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:45:49 25 4
gpt4 key购买 nike

我正在尝试创建一个从 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 调用它时,甚至手动指定所有 模板类型名称时,clang++ 3.4 表示:

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

最佳答案

问题是 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

关于c++ - Cryptic template 模板参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18220714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com