【问题标题】:Why am I getting "no matching function for call to '…'" with template function?为什么我使用模板函数得到“调用'...'没有匹配的函数”?
【发布时间】:2015-06-29 18:26:13
【问题描述】:

使用以下代码:

ma​​teria.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

ma​​terias.h:

#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

ma​​in.cpp

#include "materia.h"
#include "materias.h"
#include "confdef.h"

int main()
{
  material::MakeMaterial(WOOD, 500); // Same error here
}

Here是上述代码的在线版本,可以重现错误。)

我在注释行收到以下编译错误消息:

没有匹配的函数调用“MakeMaterial”

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

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

【问题讨论】:

  • 请先编译(阅读并理解错误信息,或询问错误信息的含义)。
  • 这不应该是第一个(或者您可能忽略了警告)
  • @DieterLücking "候选模板被忽略:无法推断模板参数'类型'"
  • 只需将两个template替换为`template``用于专业化
  • MakeMaterial 的第一个函数参数的目的是什么?是真的需要某样东西的实例,还是只是需要的类型?

标签: c++ templates compiler-errors overload-resolution explicit-instantiation


【解决方案1】:

通话中

MakeMaterial(Config, Volume); // Error here

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

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

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

如何解决这个问题取决于您要完成的任务。

【讨论】:

  • 我试图让编译器从Config 的类型中推断出type。通过显式实例化,我告诉如果Configsolidmaterial 类型,那么typesolid。我在main 中调用的内容不应该完全明确吗?
  • @zenith:好的,你在尝试这么说。但编译器只看到这是一种可能性。您可以定义任意数量的具有相同T::configtype 的其他可能性。
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-03
  • 2013-01-26
相关资源
最近更新 更多