将引用作为参数传递给模板化函数

时间:2012-08-19 16:47:22

标签: c++ templates

我有一个模板化的函数,它为给定的类分配内存并调用它的构造函数。 例如:

template <class T, class arg0>
inline T* AllocateObject(arg0 a0) { return new (InternalAllocate(sizeof(T))) T(a0); }
template <class T, class arg0, class arg1>
inline T* AllocateObject(arg0 a0, arg1 a1) { return new (InternalAllocate(sizeof(T))) T(a0,a1); }

当我通过值或指针传递任何东西时它工作正常,如:

int myInt = 5;
int* myIntPointer = &myInt;

MyClass1* myCls1 = AllocateObject<MyClass1>(myInt);     // a class with int in its constructor
MyClass2* myCls2 = AllocateObject<MyClass2>(myIntPointer);    // a class with int ptr in its constructor

然而,当我尝试通过引用传递任何东西时它不起作用,比如

int& myIntRef = myInt;

MyClass3* myCls3 = AllocateObject<MyClass3>(myIntRef, myIntRef);     // a class with two int ref in its constructor

当我尝试这样做时,我会收到如下错误:

error C2893: Failed to specialize function template
error C2780: 'T *IMemoryAllocator::AllocateObject(arg0)' : expects 1 arguments - 2 provided

..即使MyClass3构造函数接受两个参数,然后模板应选择带有2个参数的版本。这就像模板不知道选择哪个功能。

为什么会这样?

由于

1 个答案:

答案 0 :(得分:-1)

尝试std::remove_reference模板。

template <class T, class arg0>
inline T* AllocateObject(arg0 a0) { return new (InternalAllocate(sizeof(T))) T(std::remove_reference<arg0>::type(a0)); }

或者,即使是使用static_cast的更多c ++方式:

template <class T, class arg0>
inline T* AllocateObject(arg0 a0) { return new (InternalAllocate(sizeof(T))) T(static_cast<std::remove_reference<arg0>::type>(a0)); }