C++ 消除函数指针的歧义
要在两个比较函数之间进行选择,我可以编写以下代码:C++ 消除函数指针的歧义,c++,stl,C++,Stl,要在两个比较函数之间进行选择,我可以编写以下代码: 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_typ
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);
template<typename _Tp> inline const _Tp& max(const _Tp& __a, const _Tp& __b);
template<typename _Tp> inline _Tp max(initializer_list<_Tp> __l);
但不幸的是,在这种情况下
const float& (*cmp)(const float&, const float&)(&std::max);
std::max的两个定义在?:表达式中发生冲突:
const float& (*cmp)(const float&, const float&)(cmp_type >= 0 ? &std::max : &std::min);
template<typename _Tp> inline const _Tp& max(const _Tp& __a, const _Tp& __b);
template<typename _Tp> inline _Tp max(initializer_list<_Tp> __l);
模板内联常量Tp&max(常量Tp&a,常量Tp&b);
模板内联最大值(初始值设定项列表);
导致编译错误
我的选择是什么?:表达式工作?您可以制作一个
typedef
并使用它来static\u 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);
使用cmp\u t=const float&(*)(const float&,const float&);//类型定义
cmp\u t cmp=cmp\u类型>=0?静态(标准::最大值):
静态浇铸(标准:最小值);
您可以制作一个typedef
并使用它来static\u 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);
使用cmp\u t=const float&(*)(const float&,const float&);//类型定义
cmp\u t cmp=cmp\u类型>=0?静态(标准::最大值):
静态浇铸(标准:最小值);
看起来您需要使用初始化赋值:const float&(*cmp)(const float&,const float&)=(cmp\u type>=0?&std::max:&std::min)代码>@owacoder:那没用&std::max
仍在使用重载函数的地址,这样的表达式只能在发生重载解析的上下文中使用。?:
中的子表达式不是这样的上下文。看起来您需要使用初始化赋值:常量浮点和(*cmp)(常量浮点和,常量浮点和)=(cmp\u type>=0?&std::max:&std::min)代码>@owacoder:那没用&std::max
仍在使用重载函数的地址,这样的表达式只能在发生重载解析的上下文中使用。?:
中的子表达式不是这样的上下文。