简体   繁体   English

mycomparison是对象,函数还是函数指针?

[英]Is mycomparison a object , function or function pointer?

I was going through following code: 我正在通过以下代码:

template <typename String>
void test_decimals()
{
  SensibleLessThan<String> mycomparison;
  String lhs = "1.212";
  String rhs = "1.234";
  CHECK_EQUAL(mycomparison(lhs, rhs), true); // CHECK EQUAL is macro

}

I do not understand the meaning of the following constructs: 我不明白以下结构的含义:

  • SensibleLessThan<String> mycomparison;

  • mycomparison(lhs, rhs)

Is mycomparison an object, a function or a function pointer? mycomparison是一个对象,一个函数还是一个函数指针?

SensibleLessThan<String> is a type. SensibleLessThan<String>是一种类型。 mycomparison is an object of that type. mycomparison是该类型的对象。 Now it appears that the type overloads operator() , which allows it to be called as though it were a function. 现在看来,类型重载了operator() ,它允许它被调用,好像它是一个函数。 Objects of such types are usually known as function objects or functors . 这类对象通常称为函数对象仿函数 Such objects are, like functions, considered callable . 与功能一样,这些对象被认为是可调用的

For a simple example, here's an adder struct that overloads operator() . 举个简单的例子,这里是一个重载operator()adder结构。 We can create an object of the adder type and then use that object as though it were a function. 我们可以创建一个adder类型的对象,然后使用该对象就像它是一个函数一样。

#include <iostream>

struct adder
{
  int operator()(int a, int b) { return a + b; }
};

int main()
{
  adder my_adder;
  std::cout << my_adder(5, 6) << std::endl;
}

Here it is in action . 这是在行动 In fact, a similar type already exists in the C++ standard library: std::plus . 事实上,C ++标准库中已经存在类似的类型: std::plus

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

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