功能模板不是普通功能

时间:2014-07-29 17:52:20

标签: c++ templates

为什么以下代码会给我们编译错误:

#include <iostream>
using namespace std;

int i = 0;

struct A
{
    void * operator new [] (size_t t)
    {
        cout << "allocation" << endl;
        return ::operator new[](t);
    }

    template <class T>
    void operator delete [] (void *p, size_t)
    {
        cout << "deallocation" << endl;
        return ::operator delete[](p);
    }
};

int main() 
{
    A *a = new A[10];
    delete [] a;//No suitable deallocation function
}

demo

我认为function template只是一个匹配适当模板的家庭功能。这意味着必须在结构定义中找到非放置函数。

1 个答案:

答案 0 :(得分:1)

您的运算符delete[]采用void*,但其模板参数T未在函数签名中用作参数类型,因此编译器无法解析函数调用。

你想:

void operator delete [] (void *p, size_t);