如何以非内联方式为专用模板提供额外的成员函数?即
template<typename T>
class sets
{
void insert(const int& key, const T& val);
};
template<>
class sets<bool>
{
void insert(const int& key, const bool& val);
void insert(const int& key){ insert(key, true); };
};
Run Code Online (Sandbox Code Playgroud)
但是,当我写sets<bool>::insert(const int& key)的
template<>
class sets<bool>
{
void insert(const int& key, const bool& val);
void insert(const int& key);
};
template<>
void sets<bool>::insert(const int& key)
{
insert(key, true);
}
Run Code Online (Sandbox Code Playgroud)
海湾合作委员会抱怨:
'void ip_set :: insert(const int&)'的template-id'insert <>'与任何模板声明都不匹配
Geo*_*che 11
除了Effo所说的,如果你想在专业化中添加额外的功能,你应该将常用功能移动到基本模板类中.例如:
template<typename T>
class Base
{
public:
void insert(const int& key, const T& val)
{ map_.insert(std::make_pair(key, val)); }
private:
std::map<int, T> map_;
};
template<typename T>
class Wrapper : public Base<T> {};
template<>
class Wrapper<bool> : public Base<bool>
{
public:
using Base<bool>::insert;
void insert(const int& key);
};
void Wrapper<bool>::insert(const int& key)
{ insert(key, true); }
Run Code Online (Sandbox Code Playgroud)
那是因为它不是你模板的功能所以不要使用"template <>".删除"template <>"后它对我有用,如下所示:
void sets<bool>::insert(const int& key)
{
insert(key, true);
}
Run Code Online (Sandbox Code Playgroud)
我的系统FC9 x86_64.
整个代码:
template<typename T>
class sets
{
public:
void insert(const int& key, const T& val);
};
template<>
class sets<bool>
{
public:
void insert(const int& key, const bool& val) {}
void insert(const int& key);
};
void sets<bool>::insert(const int& key)
{
insert(key, true);
}
int main(int argc, char **argv)
{
sets<bool> ip_sets;
int key = 10;
ip_sets.insert(key);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3463 次 |
| 最近记录: |