gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:00:46 27 4
gpt4 key购买 nike

在下面的代码示例中,对 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com