首页 > 解决方案 > 当类可以转换为函数类型时函数如何重载

问题描述

最近我正在阅读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)呢?

标签: c++overloading

解决方案


在调用站点中activatefuncObj是一个 const 引用。因为IndirectFunctor::operator()不是 const 成员函数,所以它不是funcObj(3, 5).

使函数调用运算符 const ( IndriectFunctor::operator() const) 或将参数更改activate为不是 const ( void activate(IndirectFunctor &funcObj))。


推荐阅读