代理呼叫功能如何工作?

时间:2012-07-06 01:28:44

标签: 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;
}

3 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:1)

这些只是用户定义的转换运算符。用户定义的转换运算符是C ++语言的基本特性,这意味着您可以在C ++书籍或某些教程中阅读它们。

语言规范的第12.3.2节描述了语法,但是编译器使用它们的规则分散在整个文档中并且相对广泛。即它不是可以或应该在SO帖子中解释的东西。

找一本书。如果你不清楚书中的内容,请回到这里。

答案 2 :(得分:1)

电话callable(10);实际上是*(callable.operator void(*)(int))(10);

编译器已经发现函数调用表达式中使用了callable。现在,对于函数调用表达式,编译器希望函数,函数指针或具有operator()的对象 - 正如您所知。

在这种情况下,callable不是这些。但callable可以转换到其中一个,即函数指针。给定调用表达式,特别是int参数,重载决策选择void(*)(int)