Hi there. I am trying to check for a template type if it is a pointer, basically my goal is to create a container class, which will know how to compare objects irrespectively if the object is pointer or not. I want a class to dynamically select comparing method. My current code is below, but it doesn't work and I don't know where is a problem. It always selects
compare_ptr
as comparing method. Below code
std::vector<int> vec;
vec.push_back(1);
int test = 0;
for (const int& val : vec)
{
bool b = compare(val, test);
}
gives this error:
main.cpp:111: error: invalid type argument of unary ‘*’ (have ‘int’)
return *obj1 == *obj2;
I would greatly appreciate your help. Thanks.
What I have tried:
template<typename Type>
struct is_shared_ptr { static const bool value = false; };
template<typename Type>
struct is_shared_ptr<std::shared_ptr<Type>> { static const bool value = true; };
template <class T>
static bool compare_ptr(const T& obj1, const T& obj2)
{
return *obj1 == *obj2;
}
template <class T>
static bool compare_obj(const T& obj1, const T& obj2)
{
return obj1 == obj2;
}
template <class T>
static bool compare(const T& obj1, const T& obj2)
{
if (is_shared_ptr<T>::value)
{
return compare_ptr(obj1, obj2);
}
else
{
return compare_obj(obj1, obj2);
}
}