c++ - 如何将 std::unordered_map 部分特化为模板类的成员?

标签 c++ templates unordered-map

我似乎无法理解为什么这不起作用:

#include <unordered_map>
#include <vector>

template<typename T>
struct Bar {
    Bar(const T &t) : x{t} {}
    T x;
};

template<typename T>
struct Foo {
    std::unordered_map<T, Bar<T>> u;

    Foo(const std::vector<T> &v) {
        for (const T &i : v)
            u[i] = Bar(i);
    }    
};

int main() {
    Foo<int> f({1, 2, 3});
}
Try it here
我想要的是有一个 Foo 实例,它包含一个 unordered_map ,它将 T 类型的对象映射到 Bar 类型的对象。不幸的是,错误消息没有我希望的那么有用:error: no matching function for call to 'Bar<int>::Bar()'这里发生了什么?我该如何解决这个问题?

最佳答案

正如@songyuanyao 非常聪明地注意到,问题是std::unordered_map::operator[]返回对映射类型的引用,这需要一个不带参数的构造函数。使用 std::unordered_map::insert无需在 bar 中引入此类构造函数即可解决此问题:

#include <unordered_map>
#include <vector>

template<typename T>
struct Bar {
    Bar(const T &t) : x{t} {}
    T x;
};

template<typename T>
struct Foo {
    std::unordered_map<T, Bar<T>> u;

    Foo(const std::vector<T> &v) {
        for (const T &i : v)
            u.insert({i, Bar<T>(i)});
    }    
};

int main() {
    Foo<int> f({1, 2, 3});
}
Try it here

关于c++ - 如何将 std::unordered_map 部分特化为模板类的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68051937/

相关文章:

C++ unordered_map 没有从命令行参数中找到值

c++ - (struct PToMTraits<U V::*>) 模板规范是什么意思?

c++ - 一个扭曲的高低游戏

c++ - 性能分析器 : How to use unsigned long to measure time in microseconds?

c++ - C++ 中带有约束类型的可变参数函数添加

c++ - 初始化类中的模板对象 (c++)

C++ 模板和 C 预处理器

c++ - 如何在带有来自 std::string 的 unordered_map 的字符串文字上使用 is_transparent 功能?

c++ - 在 unordered_map 的键上实现 "did you mean"

c++ - 有什么方法可以防止命名空间在 C++ 中添加更多类?