Home > Backend Development > C++ > body text

Can you get a function pointer to a built-in standard operator in C ?

Barbara Streisand
Release: 2024-10-25 22:10:28
Original
104 people have browsed it

Can you get a function pointer to a built-in standard operator in C  ?

Is it possible to get the function pointer of a built-in standard operator?

Why built-in operators don't have function pointers

C 11 defines built-in operators in [over.built] and specifies that these operators participate in overload resolution but serve no other purpose. As such, you cannot have function pointers that point to them.

Working with function objects

To address this issue, the standard introduces function objects in [function.objects]. These objects can decay to their corresponding operators in their operator() function:

  • Arithmetic operations
  • Comparisons (equal_to, not_equal_to, greater/less, greater_equal/less_equal)
  • Logic operations
  • Bitwise operations

Function objects can be used as function pointer arguments, as demonstrated in the response provided by user1034749.

Using standard class type operators

For standard library operators, you can use them as function pointers, although you need to refer to their respective template instances. The compiler requires sufficient hints to deduce the correct template. Here's an example:

<code class="cpp">#include <iostream>
#include <string>

using namespace std;

template<class Test>
Test test_function(Test const &a, Test const &b, Test (*FPtr)(Test const &, Test const &))
{
   return FPtr(a, b);
}

int main()
{
   typedef basic_string<char> String;
   String a("test"), b("test2");
   cout << test_function(a, b, &operator+);
   return 0;
}</code>
Copy after login

In this example, the operator is provided as a function pointer for the test_function. Note that if you omit the template argument for test_function, the deduction will fail in some compilers like MSVC 2012.

The above is the detailed content of Can you get a function pointer to a built-in standard operator in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!