我有一个模板函数,它为给定的类分配内存并调用它的构造函数。例如:
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 个参数的版本。就像模板不知道选择哪个功能一样。
为什么是这样?
谢谢