I thought that I needed a specialized function for the template, but https://stackoverflow.com/a/2128321/2168168 makes me think that I really have to perform the overload function, However, I just don’t see how I could achieve that what I want.
I managed to achieve the goal with the specialization of the class template, but I do not like the fact that I have so much replicated code between the template class and the specialized class.
I have a class, among other things, two keys that are used to sort the objects of a class. In addition, I want to create a method match()that will return true for the string if the original part of the string matches (that is, "aaa" will match "aaa: zzz", because the first three characters of both lines are "aaa",), but ints shorts etc. will only match if it is an exact match (i.e. 1 == 1).
I got this to work using class specialization, as shown below:
template <class KEY2_TYPE>
class policy_key_c
{
public:
policy_key_c (int _key1,
KEY2_TYPE _key2) :
key1(_key1),
key2(_key2)
{};
virtual ~policy_key_c(void) {};
virtual std::string strIdx (void) const {
}
virtual bool operator< (const policy_key_c &b) const {
return (operator<(&b));
}
virtual bool operator< (const policy_key_c *p) const {
if (key1 < p->key1) {
return (true);
}
if (!(key1 == p->key1)) {
return (false);
}
return (key2 < p->key2);
}
virtual bool operator== (const policy_key_c &b) const {
return(operator==(&b));
}
virtual bool operator== (const policy_key_c *p) const {
if ((key1 != p->key1)) {
return (false);
}
return (key2 == p->key2);
}
virtual bool match (const policy_key_c &b) const {
return(operator==(&b));
}
virtual bool match (const policy_key_c *p) const {
return (operator==(p));
}
protected:
int key1;
KEY2_TYPE key2;
};
template <>
class policy_key_c<std::string>
{
public:
virtual bool match (const policy_key_c &b) const {
return(operator==(&b));
}
virtual bool match (const policy_key_c *p) const {
return (key2.substr(0, p->key2.lenght()) == p->key2);
}
protected:
int key1;
std::string key2;
};
I don't like this solution because there is so much replicated code. The only thing that behaves differently is the coincidence function. When key2 is an int, short or char match, it behaves like == wherease, if key2 is std :: string, I want it to do a prefix match.
? ? , , . .
.
10/12/10
PigBen , . , . , .
template <int KEY1_VAL, class KEY2_TYPE> class policy_key_c
typdefs, :
typedef policy_key_c<1, int> int_policy;
typedef policy_key_c<2, std::string> str_policy;
, , , .
10/12/10
PigBen , .
, , , . . ,
- ( ).