Home  >  Article  >  Backend Development  >  ## Can You Get Function Pointers to C Built-in Operators?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 11:52:30116browse

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

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

The Challenge

To use function pointers to reference built-in operators like the "greater than" operator (">") in a template class, it's necessary to specify the correct type overloads. However, this can be challenging.

Why Built-in Operators Can't Be Function Pointers

C built-in operators, such as the arithmetic and logical operators, are not real operator functions. Instead, they are directly translated into assembly instructions by the compiler. Therefore, it's not possible to obtain function pointers for them.

Function Objects as an Alternative

Function objects, defined in the C standard, provide a way to work with operations that behave like function pointers but are not actual functions. They are templated objects that decay to the analogous operator in their operator() function.

For example, the std::greater function object represents the greater-than operator (">"). It can be used as a function pointer argument in a template class.

<code class="cpp">template<typename ParamsType, typename FnCompareType>
class MyAction
{
public:
    MyAction(ParamsType& arg0, ParamsType& arg1, FnCompareType& fnCpmpare) 
    : arg0_(arg0), arg1_(arg1), fnCompare_(fnCompare_) {}

    bool operator()()
    {
        if((fnCompare_)(arg0_,arg1_))
        {
            // Do this
        }
        else
        {
            // Do s.th. else
        }
    }

private:
    ParamsType& arg0_;
    ParamsType& arg1_;
    FnCompareType& fnCompare_;
}</code>
<code class="cpp">void doConditional(int param1, int param2)
{
    MyAction<int, std::greater<int>> action(param1, param2);
    if(action())
    {
        // Do this
    }
    else
    {
        // Do that
    }
}</code>

Standard Class Type Operators

While function pointers cannot be used directly with built-in operators, they can be used with standard library operators that are implemented as actual functions. However, it's necessary to instantiate the specific instance of the template class for the operator, and the compiler may require hints to correctly deduce the template argument.

The above is the detailed content of ## Can You Get Function Pointers to C Built-in Operators?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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