"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ## Can You Get Function Pointers to C++ Built-in Operators?

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

Published on 2024-11-07
Browse:572

## 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.

template
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_;
}
void doConditional(int param1, int param2)
{
    MyAction> action(param1, param2);
    if(action())
    {
        // Do this
    }
    else
    {
        // Do that
    }
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3