Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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);
    }
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900