我以为我想模板功能专业化,但this stackoverflow article让我觉得我应该真的通过做功能重载。但是,我只是没有看到我如何能够实现我想要的。类模板专业化对功能重载
我已经能够实现类模板专业化的目标,但我不喜欢这样的事实,我有这么多的模板类和专门的类之间复制代码。
我所拥有的是一个类,其中包含用于排序类对象的两个键。此外,我想创建一个方法match()
,如果字符串的起始部分匹配(即,由于两个字符串的前三个字符都是'aaa'),所以字符串将返回true(即,“aaa”将匹配“aaa:zzz”),但是整数,短裤等只有匹配完全匹配时才会匹配(即1 == 1)。
我得到这个使用类专业化的工作,如下图所示:
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 {
// combine key1 and key2 into an index to be returned.
}
//
// operator <
//
virtual bool operator< (const policy_key_c &b) const {
return (operator<(&b));
}
virtual bool operator< (const policy_key_c *p) const {
// if the primary key is less then it's less, don't check 2ndary
if (key1 < p->key1) {
return (true);
}
// if not less then it's >=, check if equal, if it's not equal then it
// must be greater
if (!(key1 == p->key1)) {
return (false);
}
// its equal to, so check the secondary key
return (key2 < p->key2);
}
//
// operator ==
//
virtual bool operator== (const policy_key_c &b) const {
return(operator==(&b));
}
virtual bool operator== (const policy_key_c *p) const {
// if the primary key isn't equal, then we're not equal
if ((key1 != p->key1)) {
return (false);
}
// primary key is equal, so now check the secondary key.
return (key2 == p->key2);
}
//
// match
//
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; // The primary key
KEY2_TYPE key2; // The secondary key.
// ... other class data members ....
};
// Now specialize the template for a string as the secondary key
//
template <>
class policy_key_c<std::string>
{
public:
//
// .... all the other functions
//
//
// match
//
virtual bool match (const policy_key_c &b) const {
return(operator==(&b));
}
virtual bool match (const policy_key_c *p) const {
// do a prefix string match rather than a complete match.
return (key2.substr(0, p->key2.lenght()) == p->key2);
}
protected:
int key1; // The primary key
std::string key2; // The secondary key.
// ... other class data members ....
};
,因为有这么多的重复代码,我不喜欢这样的解决方案。唯一表现不同的是匹配功能。当key2是int时,short或char匹配的行为就像== wherease,如果key2是std :: string我希望它做一个前缀匹配。
有没有“更高效”的方式来做到这一点?这可以通过函数重载匹配函数来完成吗?如果它可能超载,我将不胜感激想法。我已经尝试了一些重载的变体,并且失败了。
在此先感谢。
编辑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的建议解决了这个问题的说明。
后来我意识到我的问题有点不同,有两个模板参数,我试图只专注于一个。这真的改变了这个问题。它看起来像我 需要做一些像完成here(这是类似于詹姆斯麦克奈利斯建议的解决方案)。
专业化的这些功能看起来与一般形式的功能相同。我错过了什么吗? – 2010-10-12 01:27:33
Bah!你是对的。假设专业化的match()函数是不同的。我编辑了代码以正确反映这一点。抱歉。 – 2010-10-12 03:36:07
击败了我。 +1 – wheaties 2010-10-12 17:16:03