简体   繁体   中英

Function Pointer of an Operator in C++

So I have a function that expects a function pointer as an input and whose prototype goes something like this:

int function(int (*op)(int, int));

I was wondering if I can pass an operator in for that function pointer. Specifically this built in operator:

int operator|(int, int);

I've tried this:

function(&(operator|));

and got this kind of error:

error: no matching function for call to 'function(<unresolved overloaded function type>)'

I've tried this:

function(&(operator|(int, int)));

and got this kind of error:

error: expected primary-expression before 'int'

I've looked for this situation in documentation, but I get things about the "address of" operator (operator&) instead of things about the address of an operator....

Edit:

See previous question Calling primitive operator-functions explicitly in C++

The built-in operator | that takes two int and returns an int can not be accessed through the notation operator| . For instance, the following does not compile

int a = operator|(2,3);

Because operators aren't available as functions, the standard provides a series of functors corresponding to operators. The most well known of these is std::less which is the default template parameter for ordering sorts, sets, and maps.

The full list can be found in the functional header. The one closest to your requirements is std::bit_or .

Unfortunately these are implemented as template classes with operator() rather than functions, so they won't be suitable for your specific use case. They're more suited for templates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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