简体   繁体   English

用于将指针传递给模板化函数的语法

[英]syntax for passing pointer to templated function

One version of my code works. 我的代码的一个版本有效。 Another (which I would have thought was preferable) fails to compile. 另一个(我本以为最好的)无法编译。 If I declare the simple pair of functions: 如果我声明简单的一对函数:

template<class T>
void pass_function(T (*func))
{
  cout << func() << endl;
}

double func_to_pass()
{
  return(0);
}

I can call 我可以打电话

pass_function(&func_to_pass);

and everything works as expected. 一切都按预期进行。 I know that it is "figuring out" that the template is standing for a double here even though I haven't told it that it is a double in this call. 我知道,即使我没有告诉它模板在此调用中是双精度型,也正在“弄清楚”模板在此处代表双精度型。

But, if instead I call 但是如果我打电话给

pass_function<double>(&func_to_pass);

I, naively, would think this would be better since I am trying to tell it that the function passed as the argument will return a double. 我天真地认为这会更好,因为我试图告诉它作为参数传递的函数将返回一个double。 But I get the error: 但是我得到了错误:

error: no matching function for call to ‘pass_function(double (*)())’

So, clearly I am misunderstanding something about the syntax of using templates. 因此,很明显,我对使用模板的语法有误解。

Change the definition like 像这样更改定义

template<class T>
void pass_function(T (*func)())
{
  cout << func() << endl;
}

Otherwise when you explicitly specify the template argument the function is specialized like 否则,当您显式指定模板参数时,该函数将像

void pass_function( double  * );

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

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