【发布时间】: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 = {
^~~~~~~
【问题讨论】:
-
向量中的所有对象都需要具有相同的编译时类型。如果要存储不同类型的对象,请使用具有公共基类的多态对象。