我想使用任何 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/