简体   繁体   English

在struct中定义operator()函数

[英]Defining operator() function inside a struct

While going through one of the tutorials in the Boost library on function wrappers here , I came across the following code: 这里通过函数包装器浏览Boost库中的一个教程时,我遇到了以下代码:

  1     boost::function<float (int x, int y)> f;
  2
  3     struct int_div {
  4         float operator() (int x, int y) const { return ((float)x)/y; }
  5     };
  6
  7
  8     int main()
  9     {
 10         f = int_div();
 11         cout << f(5, 3) << endl;
 12         return 0;
 13     }

I am trying to wrap my head around about defining a function ( operator() ) inside a struct, and then assigning the struct (using () ) to the function wrapper f . 我试图围绕在struct中定义一个函数( operator() ),然后将struct(using () )赋值给函数包装器f Can someone please help me understand what is happening, as far as concepts, in lines 3-5 and 10. 在第3-5和第10行中,有人可以帮助我了解正在发生的事情。

In C++, you can provide operators for your types. 在C ++中,您可以为类型提供运算符。 As function call ( () ) is just another operator in the language, it's possible to define it for your types. 由于函数调用( () )只是该语言中的另一个运算符,因此可以为您的类型定义它。 So the definition inside int_div says "objects of type int_div can have the function call operator applied to them (with operands int and int ); such a call will return a float ." 所以int_div的定义说“ int_div类型的int_div可以将函数调用运算符应用于它们(使用操作数intint );这样的调用将返回一个float 。”

boost::function is a wrapper around anything callable. boost::function是任何可调用的包装器。 Since an object of type int_div can be used with the function call operator, it's callable and can thus be stored in a boost::function . 由于int_div类型的对象可以与函数调用运算符一起使用,因此它是可调用的,因此可以存储在boost::function The types match as well - the operator in int_div is indeed of type float(int, int) . 类型也匹配 - int_div的运算符确实是float(int, int)

The parentheses on line 10 are not a call of this operator, however; 但是,第10行的括号​​不是该运算符的调用; they are a constructor call. 他们是构造函数调用。 So the line says "create an object of type int_div using the default constructor of that type, and assign that object into f ." 所以该行说“使用该类型的默认构造函数创建int_div类型的对象,并将该对象分配给f 。”

If you were using C++11, you could write line #10 as: 如果您使用的是C ++ 11,则可以将第10行编写为:

f = int_div{};

which probably help with your confusion. 这可能有助于你的困惑。 This line creates a temporary object of type int_div , and then assigns it to f . 此行创建一个int_div类型的临时对象,然后将其分配给f

It's not a function call, even though it looks like one. 这不是一个函数调用,即使它看起来像一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM