c++ - 当类可以转换为函数类型时函数如何重载
问题描述
最近我正在阅读c++ 模板。附录 B.3.4 中有一个模棱两可的例子,我添加了一些细节来编译。
#include <stdio.h>
typedef void FuncType(double, int);
void f(double, int) {
printf("call %s\n", __func__);
}
class IndirectFunctor {
public:
void operator()(double, double) {
printf("call %s\n", __func__);
}
operator FuncType*() const { return &f; }
};
void activate(IndirectFunctor const& funcObj) {
funcObj(3, 5);
}
int main(int argc, char* argv[]) {
IndirectFunctor funcObj;
activate(funcObj);
return 0;
}
它说当类具有对函数运算符的强制转换时,具有隐式参数的代理函数将被添加到重载决议集合中,因此调用operator FuncType*() const
需要强制IndirectFunctor&
转换FuncType*
的优先级不高于 member operator()(double, double)
。
但是代码调用operator FuncType*() const
,为什么operator FuncType*() const
有优先级operator()(double, double)
呢?
解决方案
在调用站点中activate
,funcObj
是一个 const 引用。因为IndirectFunctor::operator()
不是 const 成员函数,所以它不是funcObj(3, 5)
.
使函数调用运算符 const ( IndriectFunctor::operator() const
) 或将参数更改activate
为不是 const ( void activate(IndirectFunctor &funcObj)
)。
推荐阅读
- java - 合并通量的 Spring Webflux 类型安全性
- java - 获取 PDFBox 中的文本颜色
- spring-batch - Spring批处理-预加载块相关数据
- python-2.7 - 想要将数据推入/拉出 SalesForce Accounts/leads 从/到我的外部 Web 应用程序
- php - 如何将 PHP 数组转换为 json 字符串
- php - 致命错误:类:找不到 SQLi - 无法将 mySqli 连接到 WAMP
- angular - 清除输入下方的输入字段已更改
- mysql - 返回中间字符串并计数
- c++ - 将位图设置为 CStatic 对象
- python - python:过滤具有特定值中匹配字符串的字典