4

这是类似于我在“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;
}
4

3 回答 3

8

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

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

于 2012-07-06T01:32:36.067 回答
1

调用callable(10);实际上是*(callable.operator void(*)(int))(10);.

编译器已经发现callable在函数调用表达式中使用了它。现在,对于函数调用表达式,编译器想要一个函数、函数指针或带有operator()- 的对象,正如您已经知道的那样。

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

于 2012-07-06T13:33:09.947 回答
1

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

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

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

于 2012-07-06T01:42:33.183 回答