将函数作为显式模板参数传递 [英] Pass a function as an explicit template parameter
问题描述
在下面的代码示例中,对 foo
的调用工作,而对 bar
的调用失败。 p>
如果我注释掉对 bar
的调用,代码编译,这告诉我 bar
本身就好了。那么如何正确调用 bar
?
#include< iostream> ;
using namespace std;
int multiply(int x,int y)
{
return x * y;
}
template< class F>
void foo(int x,int y,F f)
{
cout< f(x,y) endl;
}
template< class F>
void bar(int x,int y)
{
cout<< F(x,y)< endl;
}
int main()
{
foo(3,4,multiply); // works
bar< multiply>(3,4); // failed
return 0;
}
code> multiply 不是类型;它是一个值,但函数模板 bar
期望模板参数是类型。因此错误。
如果您将函数模板定义为:
template< int(* F)(int,int)> //现在它将接受乘法(即值)
void bar(int x,int y)
{
cout< F(x,y)< endl;
}
查看在线演示: http://ideone.com/qJrAe
您可以简化语法使用 typedef
as:
typedef int (int,int);
template< Fun F> //现在它将接受乘法(即值)
void bar(int x,int y)
{
cout< F(x,y)< endl;
}
In the code example below, the call to foo
works, while the call to bar
fails.
If I comment out the call to bar
, the code compiles, which tells me the definition of bar
itself is fine. So how would bar
be called correctly?
#include <iostream>
using namespace std;
int multiply(int x, int y)
{
return x * y;
}
template <class F>
void foo(int x, int y, F f)
{
cout << f(x, y) << endl;
}
template <class F>
void bar(int x, int y)
{
cout << F(x, y) << endl;
}
int main()
{
foo(3, 4, multiply); // works
bar<multiply>(3, 4); // fails
return 0;
}
The problem here is, multiply
is not a type; it is a value but the function template bar
expects the template argument to be a type. Hence the error.
If you define the function template as:
template <int (*F)(int,int)> //now it'll accept multiply (i.e value)
void bar(int x, int y)
{
cout << F(x, y) << endl;
}
then it will work. See online demo : http://ideone.com/qJrAe
You can simplify the syntax using typedef
as:
typedef int (*Fun)(int,int);
template <Fun F> //now it'll accept multiply (i.e value)
void bar(int x, int y)
{
cout << F(x, y) << endl;
}
这篇关于将函数作为显式模板参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!