开发者

Passing a vector to a template function

Here is a small function I'm trying to write to keep track of the dynamic allocations I use in my functions (tired of writing delete [] all the time).

template <class T>
T* snew(int size, vector<T*> list)
{
    T* pointer = new T[size];
    list.push_back(pointer);
    return pointer;
}

vector<float*> list;
float* myfloat1 = snew<float*>(HEIGHT*WIDTH,list);
float* myfloat2 = snew<float*>(HEIGHT*WIDTH,list);
float* myfloat3 = snew<float*>(HEIGHT*WIDTH,list);

So then when I need to clear the memory I can use:

template <class T>
void sdelete(vector<T*> list)
{
    vector<T*>::iterator it;
    for (it = list.begin(); it != list.end(); ++it){
        delete [] *it
        *it = NULL
    }
}

like this:

sdelete<float*>(list);

When I try to compile I get:

cannot convert parameter 2 from 'std::vector<_Ty>' to 'std::vector<_T开发者_JAVA百科y,_Ax>'

Not sure what it means. Thanks for the insight :)


First and foremost, you pass vector<T*> list by value, which means that it gets copied and your global list is left unchanged.

Do it like this:

template <class T>
T* snew(int size, vector<T*>& list)

As for the compilation issue, there's a typo, you're applying * one time too much, change the usages to

float* myfloat1 = snew<float>(HEIGHT*WIDTH,list);
sdelete<float>(list);

Or you could even rely on compiler's type inference and just write

float* myfloat1 = snew(HEIGHT*WIDTH,list);
sdelete(list);

But the idea as a whole is pretty much a bad one, because if you have a vector already, you don't want to do new/delete by hand. Just create a vector<float> x(HEIGHT*WIDTH); and use it, it gets removed automatically.


Use

snew<float>(HEIGHT*WIDTH,list);

or better, simply

snew(HEIGHT*WIDTH,list);

Indeed, the template argument snew is T, and you pass vector<T*>. To match vector<float*>, you must pass float.

When calling function templates however, arguments can be deduced, so you don't need to put the <float> thing at all.

However, the best advice I can give you is to forget about all this and use vector<vector<float>>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜