在下面的代码示例中,调用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;
}
Run Code Online (Sandbox Code Playgroud)
Naw*_*waz 30
这里的问题是,multiply不是一种类型 ; 它是一个值,但函数模板bar期望模板参数是一个类型.因此错误.
如果将函数模板定义为:
template <int (*F)(int,int)> //now it'll accept multiply (i.e value)
void bar(int x, int y)
{
cout << F(x, y) << endl;
}
Run Code Online (Sandbox Code Playgroud)
然后它会工作.请参阅在线演示:http://ideone.com/qJrAe
您可以使用typedefas 简化语法:
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;
}
Run Code Online (Sandbox Code Playgroud)
multiply它不是一种类型,它是一种功能.在该上下文中,它衰减为函数指针.然而,bar对于一种类型而言,它是模板化的multiply.
Nawaz已经反过来回答了问题(如何更改bar要与函数一起使用的定义),但是要回答你如何调用bar它的明确问题,你需要一个合适的类型,如下所示:
struct Type {
const int result;
Type(int x, int y): result(x * y) {}
operator int() const { return result; }
};
// usage
bar<Type>(x, y);
// (edit) a suitable type doesn't necessarily mean a new type; this works as well
// if you aren't trying to solve any specific problem
bar<std::string>(64, 64);
Run Code Online (Sandbox Code Playgroud)