繁体   English   中英

零参数函数模板显式实例化似乎不起作用

[英]Zero argument function template explicit instantiation does not seem to work

我刚刚开始学习模板编程。 我知道可以用显式和隐式两种方式实例化函数模板。 考虑下面的代码。

template <typename var>
void cool(){
   var y = 45;
   int i = 2;
}

template void cool<int>(); // instantiated here

int main(){
  cool(); // error no matching function call. why?
  cool<int>(); // works. whats the difference between both?
  return 0;
}

当我使用零参数函数模板时,会error: no matching function call for cool()即使我显式实例化它,也error: no matching function call for cool() 但是当我使用如下所示的参数时,情况并非如此

template <typename var>
void cool(var x){
   var y = 45;
   int i = 2;
}

template void cool<int>(int); // instantiated here

int main(){
  cool(24); // works
  return 0;
}

我了解显式实例化仅在函数参数具有模板类型时才有效。 如果函数的参数列表中没有模板类型,则将其忽略。 那正确吗? 或者有什么我想念的。 任何帮助表示赞赏。

显式实例化不能神奇地为编译器提供猜测模板参数应该是什么的方法。 另外,请考虑:

template <typename var>
void cool(){
   var y = 45;
   int i = 2;
}

template void cool<int>();
template void cool<char>();

int main()
{             // now, even if explicitions specializations did
              // what you think they do,
    cool();   // what should var be here, int or char?
}

显式实例化只是强制实例化,以便在其他地方只能使用声明。 如果无法推断出模板参数,则需要显式指定它们。

这就是第二个示例起作用的原因,可以从调用中推导出template参数。 显式专业化与它无关,您可以将其删除,它也将正常工作。

您不能实例化不带参数的单参数模板。 有时可以推断出参数,因此您无需显式提供它们,但仍需要提供它们。 但是,就您而言,模板参数都不是可推论的(因为它们都不作为函数参数类型的一部分出现),因此您必须自己指定所有参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM