在c++中传递函数模板作为参数
Pass a function template as a parameter in C++
例如,我想从两个序列left
和right
中获得最大值的列表,并将结果保存在max_seq
中,这些结果都是先前定义和分配的,
std::transform(left.begin(), left.end(), right.begin(), max_seq.begin(), &max<int>);
但是这不会编译因为编译器说
note: template argument deduction/substitution failed
我知道我可以在struct
或lambda
内包装"std::max"。但是有没有一种方法directly
使用std::max
没有包装?
std::max
有多个重载,因此编译器无法确定您想调用哪一个。使用static_cast
来消除歧义,你的代码就可以编译了。
static_cast<int const&(*)(int const&, int const&)>(std::max)
你应该用lambda代替
[](int a, int b){ return std::max(a, b); }
现场演示
模板展开和实例化在编译时进行。所以你只能将模板函数传递给模板。
你可以在运行时传递一个实例化的(模板化的)函数(那么它就是一个"普通的"c++函数)。
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 具有常量引用参数的函数模板专用化
- 使用可变参数函数作为模板参数
- std::span<const T> 作为函数模板中的参数
- 如何在C++中伪造虚拟可变参数函数模板?
- C++ std::functional 中的可变参数函数模板
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 三个参数函数模板令人困惑的示例
- 父可变参数函数模板专门用于子级
- C++如何将可变参数函数模板的参数包 -> 包装到 lambda 中
- 将函数传递给可变参数函数模板
- 为什么可变参数函数模板中的这个 constexpr 不是常数?
- 将多个初始值设定项列表传递到可变参数函数模板时遇到问题
- 依赖类型不明确的 c++11 可变参数函数模板重载是否不明确
- 操作可变参数函数模板的函数参数
- C++11 中的非类型可变参数函数模板
- 将可变参数函数模板的每个参数传递给返回void的函数
- 包扩展不在最后一个参数中的可变参数函数模板
- 将可变参数函数模板参数存储到联合向量中的最有效方法
- Clang 和 GCC 在解决可变参数函数模板重载时的行为不同