Home >Backend Development >C++ >**How can you use function objects to achieve the functionality of built-in operators in C ?**
In C , built-in operators lack true function pointer counterparts and do not play a role beyond overload resolution. To address this, the standard defines function objects that mirror the behavior of built-in operators.
The standard provides function objects to encapsulate arithmetic and comparison operations, such as:
These objects provide equivalent functionality to their corresponding operators and can be used as function pointer arguments.
Certain standard library operators allow for function pointers. However, this requires specifying the template type of the objects involved. For instance, to use the operator from std::basic_string, one could implement the following:
<code class="cpp">template<class Test> Test test_function (Test const &a, Test const &b, Test (*FPtr)(Test const &, Test const &)) { return FPtr(a, b); }</code>
The following code demonstrates the usage of a function object for a comparison operation:
<code class="cpp">template<typename ParamsType, typename FnCompareType> class MyAction { public: MyAction(ParamsType& arg0, ParamsType& arg1, FnCompareType& fnCompare) : 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<int, std::equal_to<int>> action(param1,param2); if(action()) { // Do this } else { // Do that } }</code>
The above is the detailed content of **How can you use function objects to achieve the functionality of built-in operators in C ?**. For more information, please follow other related articles on the PHP Chinese website!