how function overload when class can cast to function type

Viewed 39

Recently I am reading c++ templates. There is a ambiguity example in appendix B.3.4 and I add some detail to compile.

#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;
}

It says a proxy function with a implicit argument will be added to overload resolution collection when a class has a cast to function operator, thus invoking operator FuncType*() const needs to cast IndirectFunctor& to FuncType* which not have priority than member operator()(double, double).

But the code invoke operator FuncType*() const, why operator FuncType*() const have priority than operator()(double, double) ?

1 Answers

At the call site in activate, funcObj is a const reference. Because IndirectFunctor::operator() is not a const member function, it is not a viable candidate for funcObj(3, 5).

Either make the function call operator const (IndriectFunctor::operator() const) or change the parameter to activate to not be const (void activate(IndirectFunctor &funcObj)).

Related