首页 > 解决方案 > 消除函数指针的歧义

问题描述

要在两个比较函数之间进行选择,我可以编写以下代码:

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);

导致编译错误。

使 ?: 表达式起作用我的选择是什么?

标签: c++stl

解决方案


您可以制作 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);

推荐阅读