Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does surrogate call function work?

Tags:

c++

templates

Here is the source code similar to the surrogate call functions that I read on the post "Hidden features in C++"

The only part that confuses me is those operator overloaded functions. What kind of operators are they? (They certainly don't seem like ordinary operator()'s, and why is it returning a function pointer even though there is no return type specified?

Thanks!

template <typename Fcn1, typename Fcn2>
class Surrogate {
public:
    Surrogate(Fcn1 *f1, Fcn2 *f2) : f1_(f1), f2_(f2) {}

    // Overloaded operators.
    // But what does this do? What kind of operators are they?
    operator Fcn1*() { return f1_; }
    operator Fcn2*() { return f2_; }

private:
    Fcn1 *f1_;
    Fcn2 *f2_;
};

void foo (int i)
{
    std::cout << "foo: " << i << std::endl;
}

void bar (double i)
{
    std::cout << "bar: " << i << std::endl;
}

int main ()
{
    Surrogate<void(int), void(double)> callable(foo, bar);

    callable(10);       // calls foo
    callable(10.1);     // calls bar

    return 0;
}
like image 515
Jimmy Lu Avatar asked Dec 26 '22 22:12

Jimmy Lu


2 Answers

They are implicit type conversion operators to Fcn1* and Fcn2*.

In the expression "callable(10)" callable is converted by the compiler to pointer to function with int parameter, using the first one of the type conversion operators defined in Surrogate. That function is then invoked.

like image 150
Igor Nazarenko Avatar answered Jan 10 '23 12:01

Igor Nazarenko


The call callable(10); actually is *(callable.operator void(*)(int))(10);.

The compiler has figured out that callable is used in a function call expression. Now, for a function call expression the compiler would like a function, function pointer, or object with operator() - as you already know.

In this case, callable is none of these. But callable can be converted to one of these, namely to a function pointer. Given the call expression, in particular the int argument, overload resolution selects void(*)(int).

like image 42
MSalters Avatar answered Jan 10 '23 13:01

MSalters