gpt4 book ai didi

c++ - 将函数定义为显式传递或不传递的模板参数的不同方法

转载 作者:搜寻专家 更新时间:2023-10-31 00:53:39 25 4
gpt4 key购买 nike

让:

int id(int x) { return x; }

以下代码使用 GCC 编译:

template <typename F> int f2(F f, int x) { return f(x); }

int id2(int x) { return f2(id, x); }

但以下不编译:

template <typename F> int f1(int x) { return F(x); }

int id1(int x) { return f1<id>(x); }

有人可以解释一下这有什么问题吗?

最佳答案

它不会编译,因为 typename F 需要一个类型,而你给它一个函数,例如int(*F)(int) 这是一个非类型模板参数。

int id(int x) { return x; }

template <int(*F)(int)> // here
int f1(int x) { return F(x); }

int id1(int x) { return f1<id>(x); }

这可以通过 C++17 进一步简化并变得更加通用:

template <auto F> 
int f1(int x) { return F(x); }

关于c++ - 将函数定义为显式传递或不传递的模板参数的不同方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48056757/

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