【问题标题】:Templated member function call g++ error : no matching function for call模板化成员函数调用 g++ 错误:没有匹配的调用函数
【发布时间】:2013-04-26 17:55:49
【问题描述】:

g++ 在该示例上遇到错误。

我有一个类Option,其中包含一个std::string

OptionValue 继承自 Option,具有模板类型和 std::string 类型的模板化参数作为键。

OptionManagerstd::map<std::string, Option*> 中管理OptionValue OptionManager 有一个成员函数create

  template <typename T, std::string & key>
  void  create(const T & value);

g++ 如果我不调用,请不要抱怨:

  OptionManager *manager = new OptionManager;
  manager->create<int, "my_key">(3);

g++ 不喜欢create 调用,这是错误: no matching function for call to OptionManager::create(int)

如果有人能帮我指路,我非常感谢他!!! :)

代码如下:

Option.hpp

class                                   Option
{
public:
  Option(std::string & key) :
  key_(key)
  {}

  virtual ~Option()
  {}

 protected:
   std::string                           key_;
 };

OptionValue.hpp

template                                <typename T, std::string & key>
class                                   OptionValue : public Option
{
public:
  OptionValue<T, key>(T val) :
  Option(key),
  val_(val)
  {}

  virtual ~OptionValue()
  {}

private:
  T                                     val_;
};

OptionManager.hpp

class                                   OptionManager
{
public:
  OptionManager(){}
  ~OptionManager(){}
  template                              <typename T, std::string & key>
  void                                  create(const T & value)
  {
    Option                              *tmp;

    tmp = new OptionValue<T, key>(value);
    this->list_.insert(t_pair(key, tmp));
  }
private:
  std::map<std::string, Option*>                        list_;
  typedef std::map<std::string, Option*>::iterator      t_iter;
  typedef std::pair<std::string, Option*>               t_pair;

};

ma​​in.cpp

int                             main()
{
  OptionManager                 *manager;

  manager = new OptionManager;
  manager->create<int, "my_key">(3);
  return 0;
}

g++ 错误

main.cpp: In function ‘int main()’:
main.cpp:8:35: error: no matching function for call to ‘OptionManager::create(int)’
main.cpp:8:35: note: candidate is:
OptionManager.hpp:14:12: note: template<class T, std::string& key> void OptionManager::create(const T&)

【问题讨论】:

  • 这是我多年来见过的最原始的代码格式。太可怕了。

标签: c++ templates template-matching


【解决方案1】:

您的第二个模板参数是std::string &amp; 类型。您不能使用临时对象初始化它(在您的情况下,通过将字符串文字转换为 std::string 创建的对象)。

【讨论】:

  • 坦克!你帮了我很多!
猜你喜欢
  • 2017-09-26
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 2013-11-21
相关资源
最近更新 更多