为什么模板功能会"no matching function for call to '…'"?

Why am I getting "no matching function for call to '…'" with template function?

本文关键字:call to for function 功能 matching no 为什么      更新时间:2023-10-16

使用以下代码:

材料h:

#ifndef MATERIA_H
#define MATERIA_H
class material
{
public:
  template <class type>
  static material* MakeMaterial(typename type::configtype, long);
  template <class type>
  void CreateNaturalForm(typename type::configtype, long);
  … 
};
template <class type>
material* material::MakeMaterial(typename type::configtype Config, long Volume)
{
  return type::Spawn(Config, Volume);
}
#endif

材料:

#ifndef MATERIAS_H
#define MATERIAS_H
#include "materia.h"
#include "confdef.h"
class solid : public material {
public:
  typedef solidmaterial configtype;
  … 
};
template material* material::MakeMaterial<solid>(solidmaterial, long);
template <class type>
void material::CreateNaturalForm(typename type::configtype Config, long Volume)
{
  … 
  MakeMaterial(Config, Volume); // Error here
  … 
}
template void material::CreateNaturalForm<solid>(solidmaterial, long);
#endif

confdef.h:

#ifndef CONFDEF_H
#define CONFDEF_H
enum solidmaterial {
  WOOD,
  … 
};
#endif

main.cpp

#include "materia.h"
#include "materias.h"
#include "confdef.h"
int main()
{
  material::MakeMaterial(WOOD, 500); // Same error here
}

(这是上面代码的在线版本,再现了错误。)

我在评论行收到以下编译错误消息:

调用"MakeMaterial"没有匹配功能

我做错了什么?显式实例化难道不应该让编译器看到正确的函数吗?

如果我显式编写MakeMaterial<solid>,代码就会编译,但这里的重点是从Config参数推导出type。我怎样才能做到这一点?

在调用时

MakeMaterial(Config, Volume); // Error here

编译器被要求找到其中函数模板中的type::configtypeConfig的类型的匹配。

但是没有什么告诉编译器type匹配到什么:这不是一个显式实例化。

一般来说,type可以匹配数百种类型,其中type::configtype将是Config的类型。C++不支持只有一种可能类型的特殊情况。

如何解决这个问题取决于你想要完成什么。