"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ## Can You Get Function Pointers for Built-in C++ Operators?

## Can You Get Function Pointers for Built-in C++ Operators?

Published on 2024-11-08
Browse:380

## Can You Get Function Pointers for Built-in C   Operators?

Is it Possible to Get the Function Pointer of a Built-in Standard Operator?

Introduction

Function pointers provide a way to refer to specific operator functions. However, for built-in standard operators, this approach may not be straightforward. This article delves into the reasons behind this limitation and explores alternative solutions to achieve similar functionality.

Why Function Pointers Aren't Available for Built-in Operators

According to the C Standard (13.6/1), built-in operators are not regular operator functions and thus cannot have function pointers pointing to them. They solely participate in overload resolution without serving any other purpose.

Alternative: Using Function Objects

To overcome this limitation, the C Standard introduces function objects, which provide an analogous functionality to built-in operators through templated objects. For instance, for comparisons, function objects like equal_to, greater, and less_equal are defined. These objects can be used as function pointer arguments.

Example

In the code snippet provided, the goal is to compare two integers within a template class. Using the function objects technique, it can be achieved as follows:

class MyAction {
  bool operator()() {
    if (fnCompare_(arg0_, arg1_)) {
      // do this
    } else {
      // do s.th. else
    }
  }
};

Here, fnCompare_ can be a function object like std::equal_to to perform the comparison.

Standard Class Type Operators

In addition to function objects, standard library operators can also be used as function pointers. However, the respective instance of the template must be referenced. For example:

std::basic_string a("test"), b("test2");
std::cout >(a, b, &std::operator );

Conclusion

While function pointers are not directly available for built-in standard operators, the alternative solutions provided by function objects and standard class type operators allow for equivalent functionality. These alternatives enable the use of specific standard operators as function pointers, addressing the limitation presented by built-in operators.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3