代理呼叫功能如何工作?

Jim*_* Lu 4 c++ templates

这是源代码,类似于我在帖子"C++中的隐藏功能"中读到的代理调用函数

困扰我的唯一部分是运算符重载函数.他们是什么类型的运营商?(它们当然不像普通的operator()那样,为什么即使没有指定返回类型,它也会返回一个函数指针?

谢谢!

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;
}
Run Code Online (Sandbox Code Playgroud)

Igo*_*nko 8

它们是Fcn1*和Fcn2*的隐式类型转换运算符.

在表达式"callable(10)"中,编译器使用Surrogate中定义的第一个类型转换运算符将callable转换为指向带有int参数的函数的指针.然后调用该函数.