【问题标题】:C++ Template specialization to provide extra member function?提供额外成员函数的 C++ 模板特化?
【发布时间】:2009-11-09 03:53:15
【问题描述】:

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

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&lt;bool&gt;::insert(const int&amp; 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&)' 确实 不匹配任何模板声明

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    除了 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); }
    

    【讨论】:

      【解决方案2】:

      那是因为它不是模板的功能,所以不要使用“模板”。删除“模板”后它对我有用,如下所示:

      void sets<bool>::insert(const int& key) 
      { 
          insert(key, true); 
      } 
      

      我的系统 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;
      }
      

      【讨论】:

        【解决方案3】:

        我觉得你应该明白以下两点:

        1. 如果要指定类主模板,必须在指定版本声明前加上'template',但成员函数不用'template<.. .>' 在成员函数定义之前(因为指定模板类的类型信息已经被你设置好了)。

        2. 我认为主模板类与特定版本无关。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-24
          • 2012-12-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-03
          • 1970-01-01
          相关资源
          最近更新 更多