Reputation: 125
I´m running into a problem with this piece of code: First I create a class like this:
template <typename T1, typename T2> class MyClass
{
private:
std::vector<T2> m_values;
static const bool HAS_POINTER = std::is_pointer<T2>::value;
};
T2 could be, depending on the needs, either a type or a pointer. My problem is when i try to release the pointers:
template<typename T1, typename T2> void MyClass<T1, T2>::Clear()
{
if (HAS_POINTER)
{
for (int i = 0; i < m_values.size(); ++i)
delete m_values[i];
}
}
Here the compiler complains showing error C2541: Cannot delete objects that are not pointers I know the compiler is right, but the problem is T2, in some cases, IS a pointer. How do I deal with this? Thank you in advance.
Upvotes: 0
Views: 177
Reputation: 27518
You can partially specialise templates for pointers. Here is a very simple example:
#include <vector>
#include <iostream>
template <typename T1, typename T2> class MyClass
{
public:
std::vector<T2> m_values;
void Clear()
{
std::cout << "no pointers\n";
}
};
template <typename T1, typename T2> class MyClass<T1, T2*>
{
public:
std::vector<T2*> m_values;
void Clear()
{
std::cout << "pointers\n";
for (int i = 0; i < m_values.size(); ++i)
delete m_values[i];
}
};
int main()
{
MyClass<int, int> example;
MyClass<int, int*> example2;
example.Clear();
example2.Clear();
}
Upvotes: 4