S
Stanislaw Salik
Hi,
Lets suppose we want to use generic algotithms on collections of
pointers (both raw and smart). For example, we want to sort a vector of
(smart)pointers. We need a comparator that will take two pointers and
return a bool.
std::vector<std::string *> v;
std::sort(v.begin(), v.end(), std::less<int>());
The code above will noc compile, since std::less<std::string>() object
takes two strings, while we have pointers to std::string. So we need an
adaptor.
template <class T, class U>
struct pointer_to_ref
{
typedef T argument_type;
typedef U result_type;
inline
result_type & operator() (argument_type obj)
{
return *obj;
}
};
std::vector<int *> v;
std::sort(v.begin(), v.end(),
boost::bind(std::less<string>(),
boost::bind (pointer_to_ref<std::string*, std::string>(),_1),
boost::bind (pointer_to_ref<std::string*, std::string>(),_2)));
And the code will just work fine.
And here goes my question. Since there are so many places where
pointer_to_ref (and pointer_to_value probably) would be useful, is there
any standard class that does the same thing?
For example, for smart pointers i can use
&collection_type::value_type:
perator* as an adaptor. But what if i
wanted to make code more generic and working with raw pointers too?
Regards,
Stanislaw
Lets suppose we want to use generic algotithms on collections of
pointers (both raw and smart). For example, we want to sort a vector of
(smart)pointers. We need a comparator that will take two pointers and
return a bool.
std::vector<std::string *> v;
std::sort(v.begin(), v.end(), std::less<int>());
The code above will noc compile, since std::less<std::string>() object
takes two strings, while we have pointers to std::string. So we need an
adaptor.
template <class T, class U>
struct pointer_to_ref
{
typedef T argument_type;
typedef U result_type;
inline
result_type & operator() (argument_type obj)
{
return *obj;
}
};
std::vector<int *> v;
std::sort(v.begin(), v.end(),
boost::bind(std::less<string>(),
boost::bind (pointer_to_ref<std::string*, std::string>(),_1),
boost::bind (pointer_to_ref<std::string*, std::string>(),_2)));
And the code will just work fine.
And here goes my question. Since there are so many places where
pointer_to_ref (and pointer_to_value probably) would be useful, is there
any standard class that does the same thing?
For example, for smart pointers i can use
&collection_type::value_type:
wanted to make code more generic and working with raw pointers too?
Regards,
Stanislaw