c++ - 模板类作为STL容器参数

标签 c++ templates stl

我想使用任何 STL 容器,例如 std::vector 和我自己的模板类型,例如 OptionParams

如果我使用空主函数编译代码 - 一切都好,但是如果我想在容器中打印模板类的任何字段,则会出现错误。我不确定,这可能可以在 STL 容器模板类中使用。

#include <vector>
#include <map>
#include <string>
#include <iostream>

template <typename T>
struct OptionParams {
    OptionParams(int level, int name, bool is_flag, T value) : level_(level), 
            name_(name), is_flag_(is_flag), value_(value) {}
    int level_;
    int name_;
    bool is_flag_;
    T value_;
};

template <typename T>
std::vector<OptionParams<T>> Options = {
    {OptionParams<int>(1, 2, 0, 3)},
    {OptionParams<std::string>(1, 2, 1, "hello")}
};

int main() {
    std::cout << Options<int>[0].level_ << std::endl;
}
map2.cpp: In instantiation of ‘std::vector<OptionParams<int>, std::allocator<OptionParams<int> > > Options<int>’:
map2.cpp:23:16:   required from here
map2.cpp:17:30: error: could not convert ‘{{OptionParams<int>(1, 2, 0, 3)}, {OptionParams<std::__cxx11::basic_string<char> >(1, 2, 1, std::__cxx11::basic_string<char>(((const char*)"hello"), std::allocator<char>()))}}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<OptionParams<int>, std::allocator<OptionParams<int> > >’
 std::vector<OptionParams<T>> Options = {
                              ^~~~~~~

最佳答案

Options是一个变量模板,您可以使用单个参数 T 实例化它得到一个变量。当您使用 Options<int> 这样做时在main ,你最终得到 std::vector<OptionParams<int>> ,它只能存储 OptionParams<int> s,但不是 OptionParams<std::string> 。由于不同 OptionParam<T> 之间不可能进行转换s,您会收到错误。

如果您想将异构对象存储在 std::vector 中,你需要某种类型删除。例如,拥有 OptionParams<T> 的所有特化从公共(public)基类继承,并存储 std::unique_ptr到该基类。

关于c++ - 模板类作为STL容器参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58282961/

相关文章:

如果参数之一是字符串,则 C++ 返回类型等于字符串

c++ - 插入优先级队列时出现段错误

c++ - 如何将二进制数据转换为整数值

c++ - IAT Hook - 无法 Hook ExitProcess

c++ - std::set - 类似于我的容器中的函数对象支持

c++ - 具有 constexpr 函数的模板作为参数返回

c++ - 不使用 <algorithm> 从 2 个 vector (或列表)中删除相似元素

c++ - 删除列表 C++ 中的最后 3 个元素

c++ - 该对象具有与覆盖 draw 的成员函数 sfml 不兼容的类型限定符

c++ - .NET 和 Linux 之间的 GUID/UUID 兼容性问题