作为 Stl 容器参数的模板类

Template class as Stl container parameter

本文关键字:参数 Stl 作为      更新时间:2023-10-16

我想使用任何 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对其进行实例化以获取变量。当你在main中使用Options<int>这样做时,你最终会得到一个std::vector<OptionParams<int>>,它只能存储OptionParams<int>,而不能存储OptionParams<std::string>。由于不同OptionParam<T>之间没有可能的转换,因此会出现错误。

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