如何以非内联方式为专用模板提供额外的成员函数? 即
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); };
};
但是当我写 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);
}
GCC 提示:
template-id ‘insert<>’ for ‘void ip_set::insert(const int&)’ does not match any template declaration
最佳答案
除了 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); }
关于C++ 模板专门化以提供额外的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1699015/