Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将函数作为显式模板参数传递_C++_Templates - Fatal编程技术网

C++ 将函数作为显式模板参数传递

C++ 将函数作为显式模板参数传递,c++,templates,C++,Templates,在下面的代码示例中,对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 <&l

在下面的代码示例中,对
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;
}
#包括
使用名称空间std;
整数乘法(整数x,整数y)
{
返回x*y;
}
模板
无效foo(整数x,整数y,F)
{

cout这里的问题是,
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;
}

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);
结构类型{
常数int结果;
类型(intx,inty):结果(x*y){
运算符int()常量{返回结果;}
};
//用法
bar(x,y);
//(编辑)一个合适的类型并不一定意味着一个新的类型;这同样有效
//如果你不想解决任何特定的问题
巴(64,64);

如果他要使用这个,那么他也需要更改
条形图
。语法
F(x,y)
应该变成
F(x,y)(
@Nawaz No,
类型
实际上不是一个函子。它只是一个具有合适构造函数和流输出重载的类型(在本例中是一个已经有流输出重载的合适的转换运算符)。(参见)Ohh..我忽略了这一点…可能是因为函子在这里是一个更好的选择,因此我希望是这样。另请参见。
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);