c++ - 当类可以转换为函数类型时函数如何重载

标签 c++ overloading

最近我正在阅读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/

相关文章:

c++ - 为什么我不能编译这个开源项目

c# - 在 C# 中使用参数的成本

C# params 关键字和函数重载

c# - 在 C# 中解决方法重载的优先规则是什么?

c++ - Anjuta 如何改变提示框的颜色?

c++ - 如何在折叠期间获取成员类型的 boost::mpl 占位符

c++ - 在 vector 中使用共享指针来访问类对象

java - 基元和对象类型的方法重载

powershell - 在嵌套 PSObject 属性上重载 ToString 的问题

c++ - 当模态窗口最小化时最小化所有应用程序窗口(在 Linux 上)