【问题标题】:Template class as Stl container parameter模板类作为 Stl 容器参数
【发布时间】:2019-10-08 08:46:29
【问题描述】:

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

如果我用空的 main 函数编译我的代码 - 一切都好,但是如果我想在容器中打印我的模板类的任何字段,我就会出错。我不确定,这可能在 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 = {
                              ^~~~~~~

【问题讨论】:

  • 向量中的所有对象都需要具有相同的编译时类型。如果要存储不同类型的对象,请使用具有公共基类的多态对象。

标签: c++ templates stl


【解决方案1】:

Options 是一个变量模板,您可以使用单个参数 T 实例化它以获取变量。当您在main 中使用Options&lt;int&gt; 时,您最终会得到一个std::vector&lt;OptionParams&lt;int&gt;&gt;,它可以 存储OptionParams&lt;int&gt;s,但不能存储OptionParams&lt;std::string&gt;。由于不同的OptionParam&lt;T&gt;s 之间不可能进行转换,所以会出现错误。

如果你想在std::vector 中存储异构对象,你需要某种类型的擦除。例如,让OptionParams&lt;T&gt; 的所有特化都继承自一个公共基类,并将std::unique_ptrs 存储到该基类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    相关资源
    最近更新 更多