Michael
Michael

Reputation: 712

C++ templates: How to conditionally delete values by std::is_pointer

In the destructor of a general container I did, I try to delete the elements if they are pointer, so I tried below. But when I tested with T=double, the compiler showed error message that delete must be followed by pointer. How can I do this properly?

template<class T> static void deleteIfPointer(T t)
{

    if(std::is_pointer<T>::value)
    {
        std::cout << "is pointer" << std::endl;
        delete t;
    }
    else
        std::cout << "not pointer" << std::endl;

}

Upvotes: 2

Views: 359

Answers (1)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48447

template <class T>
static void deleteIfPointer(const T& t)
{
    std::cout << "not pointer" << std::endl;
}

template <class T>
static void deleteIfPointer(T* t)
//                           ^
{
    std::cout << "is pointer" << std::endl;
    delete t;
}

Upvotes: 8

Related Questions