函数模板由用于构建不同类型的容器的分配器参数化
Function template parameterized by an allocator that is used to construct containers of different types
我想要沿着这些行的函数 foo
template <class T, class Alloc>
void foo(T param, Alloc a) {
vector<int, Alloc<int> > vect_of_ints;
list<float, Alloc<float> > list_of_floats;
do_something()
}
std::allocator a
foo(42, a);
这失败了,我认为这是因为std::allocator
直到针对特定类型进行了分隔之前才是明确定义的类型。是否可以做我想做的事,但以其他方式做。
您不能有一个分配器的实例(A),并期望它适用于两种不同类型。但是,您可以使用分配器通用类型(模板模板参数),并以两种不同的方式在FOO()中进行专业化。无论如何,您都不在foo()上使用" a"。
template <template<class> class Alloc, class T>
void foo(T t1, T t2) {
vector<int, Alloc<int> > vect_of_ints;
list<float, Alloc<float> > list_of_floats;
do_something()
}
// UPDATE: You can use a function wrapper, and then the compiler will be
// able to figure out the other types.
template<class T>
void foo_std_allocator(T t1, T t2)
{
foo<std::allocator, T>(t1, t2);
}
int main()
{
//std::allocator a;
//foo<std::allocator>();
foo<std::allocator, int>(1, 2);
// in the call below, the compiler easily identifies T as int.
// the wrapper takes care of indicating the allocator
foo_std_allocator(1, 2);
return 0;
}
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- C++自定义分配器大小参数作为模板参数会引发编译器错误
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- STD ::列表对其分配器参数有什么作用
- 为什么容器的分配器作为模板参数传递
- 我应该将分配器作为函数参数传递吗?(我对分配器的误解)
- 使用SWIG生成的Python库时,向量分配器参数错误
- 在C++容器中,作为模板参数提供的分配器和作为构造函数参数提供的分配程序之间的区别
- 函数模板由用于构建不同类型的容器的分配器参数化
- 为什么shared_ptr类型没有模板分配器参数
- 带有容器和默认分配器的模板模板参数:我可以让我的声明更紧凑吗
- 'Tag' boost::p ool_分配器和 boost::fast_pool_allocator 中的模板参数是否支持控制基础池的实例?
- 分配器作为向量和列表中的默认参数
- 为什么std::list要不带参数地调用我的分配器?
- 为什么分配器类型作为模板参数而不是 ctor 的参数?
- 用于分配器类型参数的C++设计模式