mardi 4 juin 2019

c++ constrain template parameter in pointer for a template function

I am working on a code base using core c++11 language features without the support of the standard library. So everything in the namespace std is implemented by a vendor who is no longer touch c++ for several years.

The thing I am trying to do is a cleanup function which is recycling allocated memory from std::vector<T*>.

template<typename T>
void Cleanup(std::vector<T*> &v)
{
    for(T*& p : v)
    {
        delete p;
        p = nullptr;
    }
}

It kind of working. But I think it would be good to put some limitations on the input parameter, so only a pointer can be passed in the function kind like std::is_pointer<T> in the std. Any idea of how to do that without std?

#include <iostream>
#include <cstdlib>
#include <vector>
#define EOL "\n"
class A{
    public:
    A():data(0){}
    int data; 
};
class B{};

std::vector<A*> va;
std::vector<B*> vb;


int main()
{
    for(int i = 0; i<3; ++i)
    {
        va.push_back(new A());
    }

    for(int i = 0; i<5; ++i)
    {
        vb.push_back(new B());
    }


    std::cout << va.size() << " : "<<  vb.size() << std::endl;
    Cleanup(va);
    Cleanup(vb);

    for(std::size_t i = 0; i<va.size(); ++i)
    {
        if(va[i] != nullptr)
        {
            std::cout << "Failed to clean : " << va[i] << "["<< va[i]->data <<"]" << EOL; 
        }
    }
}

Any other suggestions are welcome.

Aucun commentaire:

Enregistrer un commentaire