c++中运算符的函数指针

时间:2021-10-04 18:52:24

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++

参见前面的问题,在c++中显式地调用基元操作数函数

2 个解决方案

#1


3  

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并返回int的内置操作符|不能通过符号操作符|访问。例如,下面的代码不会编译

int a = operator|(2,3);

#2


1  

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.

由于操作符作为函数不可用,因此标准提供了一系列对应于操作符的函数。其中最著名的是std::less,它是排序、设置和映射的默认模板参数。

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

完整的列表可以在函数头中找到。最接近您的需求的是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.

不幸的是,这些类是用operator()而不是函数实现的模板类,因此它们不适合您的特定用例。它们更适合模板。

#1


3  

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并返回int的内置操作符|不能通过符号操作符|访问。例如,下面的代码不会编译

int a = operator|(2,3);

#2


1  

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.

由于操作符作为函数不可用,因此标准提供了一系列对应于操作符的函数。其中最著名的是std::less,它是排序、设置和映射的默认模板参数。

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

完整的列表可以在函数头中找到。最接近您的需求的是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.

不幸的是,这些类是用operator()而不是函数实现的模板类,因此它们不适合您的特定用例。它们更适合模板。