繁体   English   中英

模板 class 作为 Stl 容器参数

[英]Template class as Stl container parameter

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

如果我用空的主 function 编译我的代码 - 一切正常,但如果我想在容器中打印我的模板 class 的任何字段,我有错误。 我不确定,这可能在 Stl 容器模板 class 中使用。

#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实例化它以获取变量。 当你在main中使用Options<int>时,你最终会得到一个std::vector<OptionParams<int>> ,它只能存储OptionParams<int> s,但不能存储OptionParams<std::string> 由于不同的OptionParam<T>之间没有可能的转换,因此您会收到错误消息。

如果要将异构对象存储在std::vector中,则需要某种类型的擦除。 例如,让OptionParams<T>的所有特化从公共基础 class 继承,并将std::unique_ptr存储到该基础 class。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM