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.
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, 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>
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!