C++ 模板专门化以提供额外的成员函数?

标签 c++ templates

如何以非内联方式为专用模板提供额外的成员函数? 即

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/

相关文章:

指向以模板作为参数的函数的 C++ 函数指针

c++ - 用于将 RGB 图像转换为灰度图像的共享内存 Cuda

c++ - 无法在 gdb 中设置断点

C++ 程序不会在 Xcode 中打印到 cout

c++ - 将 boost::optional 与常量类型一起使用 - C++

c++ - 偏特化非类型参数

c++ - g++抛出错误而不返回值

c++ - 我是否已成功从堆中删除指针?

c++ - 二进制搜索树类 - 标识符 "ItemType"未定义

c++ - 函数模板(类模板的成员)的显式特化会产生 "partial specialization is not allowed"错误,为什么?