【问题标题】:how function overload when class can cast to function type当类可以转换为函数类型时函数如何重载
【发布时间】:2021-02-08 18:39:52
【问题描述】:

最近我正在阅读 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&amp; 转换为优先级不高于成员的FuncType* operator()(double, double).

但是代码调用operator FuncType*() const,为什么operator FuncType*() const的优先级高于operator()(double, double)

【问题讨论】:

    标签: c++ overloading


    【解决方案1】:

    activate 的调用站点,funcObj 是一个常量引用。因为IndirectFunctor::operator() 不是 const 成员函数,所以它不是funcObj(3, 5) 的可行候选者。

    要么将函数调用运算符设为 const (IndriectFunctor::operator() const),要么将参数更改为 activate 使其不是 const (void activate(IndirectFunctor &amp;funcObj))。

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 2023-01-19
      • 1970-01-01
      • 2017-03-03
      • 1970-01-01
      • 2012-04-27
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多