最近我正在阅读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*
的优先级不高于成员 operator()(double, double)
。
但是代码调用了operator FuncType*() const
,为什么operator FuncType*() const
优先于operator()(double, double)
?
最佳答案
在activate
中的调用站点,funcObj
是一个常量引用。由于 IndirectFunctor::operator()
不是 const 成员函数,因此它不是 funcObj(3, 5)
的可行候选函数。
要么使函数调用运算符为 const (IndriectFunctor::operator() const
),要么将 activate
参数更改为非 const (void activate(间接仿函数 &funcObj)
)。
关于c++ - 当类可以转换为函数类型时函数如何重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66078990/