0

使用以下代码:

材料.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

材料.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

主文件

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

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

这里是重现错误的上述代码的在线版本。)

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

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

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

如果我明确地编写代码,代码就会编译MakeMaterial<solid>,但这里的重点是typeConfig参数中推断出来。我怎样才能做到这一点?

4

1 回答 1

2

在通话中

MakeMaterial(Config, Volume); // Error here

type::configtype编译器被要求在函数模板中找到匹配的类型Config

但是没有任何东西告诉编译器要匹配什么type:这不是一个显式的实例化。

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

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

于 2015-06-29T18:35:54.487 回答