vendredi 30 janvier 2015

Pass generic template class as functor parameter

I want to improve the following code snippet:



THNNetIPInfoIter last = std::unique(fist, end, HNInfoIPComparator());


where currently HNInfoIPComparator() is implemented as following:



// equal comparator
class HNInfoIPComparator
{
public:
bool operator()(const THNNetIPInfo &a, const THNNetIPInfo &b);
bool operator()(const SDK::TIPAddressDescription &a, const SDK::TIPAddressDescription &b);
bool operator()(const THNNetIPInfo &a, const SDK::TIPAddressDescription &b);
bool operator()(const SDK::TIPAddressDescription &a, const THNNetIPInfo &b);
};


The reason for this comparator definition is that it might be used with another STL algorithms, like std::set_difference and should handle case when ranges has different types.


The problem is that I have to write huge amount of very similar comparators and it is easy to be entangled with which comparator to use.


I want to write the following snippet:



template<typename SDKClass, typename IDLClass>
class equal {
public:
bool operator()(const IDLClass &a, const IDLClass &b) {
if (strcmp(a.ipaddr.in(), b.ipaddr.in())) {
return false;
}
return true;
}

bool operator()(const SDKClass &a, const SDKClass &b) {
if (strcmp(a.ip_address().c_str(), b.ip_address().c_str())) {
return false;
}
return true;
}

bool operator()(const IDLClass &a, const SDKClass &b) {
if (strcmp(a.ipaddr.in(), b.ip_address().c_str())) {
return false;
}
return true;
}

bool operator()(const SDKClass &a, const IDLClass &b) {
if (strcmp(a.ip_address().c_str(), b.ipaddr.in())) {
return false;
}
return true;
}
};


So HNInfoIPComparator() would be generated depending on types passed as its arguments inside std::unique function.


Therefore I want to pass to std::unique templated functor (class). Is it possible to do that and how?


Also I want to handle case when functor contains some internal data, which are used for comparisons


Most important code samples:



// Automatically generated structure from IDL specification
// Basically simple structure
struct THNNetIPInfo
{
typedef THNNetIPInfo_var _var_type;
typedef THNNetIPInfo_out _out_type;

static void _tao_any_destructor (void *);
::TAO::String_Manager ipaddr;
::TAO::String_Manager netmask;
};

// THNNetIPInfoIter - class external iterator
// which was written manually
typedef Util::CorbaSeqIter<THNNetIPInfoList, THNNetIPInfo> THNNetIPInfoIter;

// THNNetIPInfoList - also automatically generated class
// from IDL specification, list of THNNetIPInfo elements
THNNetIPInfoList list(...);
THNNetIPInfoIter first(&list, 0);
THNNetIPInfoIter end(&list, list.length());

Aucun commentaire:

Enregistrer un commentaire