函数模板由用于构建不同类型的容器的分配器参数化

Function template parameterized by an allocator that is used to construct containers of different types

本文关键字:参数 分配器 同类型 用于 构建 函数模板      更新时间:2023-10-16

我想要沿着这些行的函数 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;
}