【问题标题】:Error with templated function overloading and out of class definition模板化函数重载和超出类定义的错误
【发布时间】:2019-07-06 11:57:51
【问题描述】:

我正在学习游戏开发,在书中我需要使用模板重载一个函数。原来的功能是

template <typename Resource, typename Identifier>
void ResourceHolder<Resource, Identifier>::load(Identifier id, const std::string& filename)
{}

而重载的版本是

template <typename Resource, typename Identifier>
template <typename Parameter>
void ResourceHolder<Resource, Identifier>::load(Identifier id, const std::string& filename, const Parameter& secondParam)
{}

当我尝试用这个在 main 中运行代码时

ResourceHolder<sf::Texture, Textures::ID> textures;

我得到编译错误:

error: prototype for ‘void ResourceHolder<Resource, Identifier>::load(Identifier, const string&, const Parameter&)’ does not match any in class ‘ResourceHolder<Resource, Identifier>’
void ResourceHolder<Resource, Identifier>::load(Identifier id, const std::string& filename, const Parameter& secondParam)

我该如何解决这个问题? 谢谢。

【问题讨论】:

  • 请尝试创建minimal reproducible example 向我们展示。
  • 你记得在你的类中声明新的函数模板吗?
  • ` void load(Identifier id, const std::string& filename); template void load(Identifier id, const std::string& filename); ` 我的班级声明中有这些。我正在使用 .hpp 文件进行 decleration 和 .inl 进行定义,如果它有所作为。
  • 我相信您正在寻找的词是“专业化”而不是“超载”。无论如何,请发帖minimal reproducible example
  • Guillaume Racicots 解决方案有效。我的重载函数中缺少参数。谢谢大家。

标签: c++ function class templates overloading


【解决方案1】:

你忘记在你的类中添加声明:

template <typename Resource, typename Identifier>
struct ResourceHolder {
    // ...

    // member function must be in the class
    template<typename Parameter>
    void load(Identifier id, const std::string& filename, const Parameter& secondParam);
};

【讨论】:

  • ` void load(Identifier id, const std::string& filename); template void load(Identifier id, const std::string& filename); ` 我的班级声明中有这些。我使用 .hpp 文件进行 decleration 和 .inl 进行定义,如果它有所作为。
  • 那我不知道如何重现这个问题。这是我的解决方案的工作原理:godbolt.org/z/pnK-bN
  • 啊,谢谢,我的重载函数中缺少“const Parameter& secondParam”。解决了。​​
猜你喜欢
  • 1970-01-01
  • 2015-02-27
  • 2021-12-20
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多