作为 Stl 容器参数的模板类
Template class as Stl container parameter
我想使用任何 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
存储到该基类。
相关文章:
- 有没有办法捕获 STL 函数未被赋予正确参数的异常?
- C++ 如何将参数传递给 STL 函数
- C++如何获取传递给函数(STL 迭代器)的参数的名称
- 作为 Stl 容器参数的模板类
- STL 容器在函数中作为模板参数,在调用中出错
- 可以在 stl 容器上完成非类型模板参数吗?
- STL vector.insert 方法期望_InputIterator作为参数
- 模板化函数以从输入参数推断返回类型 stl-container
- IS C STL模板参数足够精确
- 如何断言模板参数的类型 STL 迭代器类型
- 为什么lambda函数用于stl函数,例如sort(),c 中的max_element()函数以两个参数为输入
- 意外参数通过使用STL数字的顺序
- 无法使用 std::function 作为参数类型(需要函数指针版本)宁愿像 STL 这样的模板,但随后它无法推断参数
- STL 按多个参数C++排序
- 模板参数适用于不同的STL容器
- 在SGI STL的实现中,向量的push_back函数不使用默认参数
- C++模板编程/STL 推导参数
- 将适当类型的迭代器作为参数返回适当类型的STL容器
- 如何将函数中的stl列表传递为C 中的参数
- 使用类作为具有正向延迟的 STL 类的模板参数