c++ - 消除函数指针的歧义
问题描述
要在两个比较函数之间进行选择,我可以编写以下代码:
const float& (*cmp)(const float&, const float&);
if (cmp_type >= 0)
cmp = &std::max;
else
cmp = &std::min;
我想使用 ?: 表达式将它组合成一行:
const float& (*cmp)(const float&, const float&)(cmp_type >= 0 ? &std::max : &std::min);
但不幸的是,在这种情况下反对:
const float& (*cmp)(const float&, const float&)(&std::max);
std::max 的两个定义在 ?: 表达式中发生冲突:
template<typename _Tp> inline const _Tp& max(const _Tp& __a, const _Tp& __b);
template<typename _Tp> inline _Tp max(initializer_list<_Tp> __l);
导致编译错误。
使 ?: 表达式起作用我的选择是什么?
解决方案
您可以制作 atypedef
并使用它来static_cast
获得正确的重载。
using cmp_t = const float&(*)(const float&, const float&); // typedef
cmp_t cmp = cmp_type>=0 ? static_cast<cmp_t>(std::max) :
static_cast<cmp_t>(std::min);
推荐阅读
- python - 如何用两组数据创建一个角图
- javascript - 有没有办法只使用 jQuery.each() 处理一个数组?
- c++ - gcc (g++) 如何链接多个库?
- elixir - 如何在 Elixir/Phoenix 中的多个并发请求之间共享结果?
- android - 如何在 key.propreties 中使用当前用户主目录
- reactjs - React - 传递没有值的道具
- python - 我的客户端程序使用 python socket api 只接受来自服务器的一个字节
- javascript - 如何在 Django 模板中调用 javaScript 函数?
- php - 如何在 PHP 中实现一个接受字符串参数并返回 JSON 格式的方法
- typescript - 打字稿编译器中的对象速记语法