作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
在下面的代码示例中,对 foo
的调用有效,而对 bar
的调用失败。
如果我注释掉对 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); // fails
return 0;
}
最佳答案
这里的问题是,multiply
不是 type;它是一个值,但函数模板bar
期望模板参数是一个type。因此出现错误。
如果将函数模板定义为:
template <int (*F)(int,int)> //now it'll accept multiply (i.e value)
void bar(int x, int y)
{
cout << F(x, y) << endl;
}
那么它就会起作用。见在线演示:http://ideone.com/qJrAe
您可以使用 typedef
将语法简化为:
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;
}
关于c++ - 将函数作为显式模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10871100/
我是一名优秀的程序员,十分优秀!