How can I specialize a template member function for std::vector

前端 未结 2 669
情话喂你
情话喂你 2020-12-15 17:26

I need to define a get method in two different ways. One for simple types T. And once for std::vector.

template
const T& Parameters::ge         


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-15 18:29

    Erm. call it something else? e.g.

    template
    const T& Parameters::getVector(const std::string& key)
    {
      Map::iterator i = params_.find(key);
      std::vector temp = boost::get >(i->second)
      // T is already a vector
      T ret; ret.reserve(temp.size());
      for(int i=0; i(temp[i]));
      }
      return ret;  
    }
    

    You'll have to call this as:

    foo.getVector > ("some_key");
    

    Nothing in your question precludes this.

    Now, if you really do need to use get(), then you have to rely on partially specializing a structure, as function partial specialization is not supported by the language.

    This is a lot more complicated, for example:

    template 
    struct getter
    {
      const T& operator()(std::string const& key)
      {
        // default operations
      }
    };
    
    // Should double check this syntax 
    template 
    struct getter > >
    {
      typedef std::vector > VecT;
      const VecT& operator()(std::string const& key)
      {
        // operations for vector
      }
    };
    

    Then in you method becomes:

    template
    const T& Parameters::get(const std::string& key)
    {
      return getter()(key); // pass the structures getter needs?
    }
    

提交回复
热议问题