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.
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.
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.
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:
<code class="cpp">class MyAction { bool operator()() { if (fnCompare_(arg0_, arg1_)) { // do this } else { // do s.th. else } } };</code>
Here, fnCompare_ can be a function object like std::equal_to
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:
<code class="cpp">std::basic_string<char> a("test"), b("test2"); std::cout << test_function<std::basic_string<char>>(a, b, &std::operator+);</code>
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.
The above is the detailed content of ## Can You Get Function Pointers for Built-in C Operators?. For more information, please follow other related articles on the PHP Chinese website!