3

我想要一个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它不是一个定义明确的类型,直到它被专门用于特定类型。是否可以做我想做的事,但以其他方式。

4

1 回答 1

4

您不能拥有分配器 (a) 的一个实例并期望它适用于 2 种不同类型。但是,您可以使用分配器泛型类型(模板模板参数),并以两种不同的方式在您的 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;
}
于 2012-11-01T06:47:28.230 回答