Functional (C++)
In the context of the programming language C++, The class template The algorithms provided by the C++ Standard Library do not require function objects of more than two arguments. Function objects that return Boolean values are an important special case. A unary function whose return type is Adaptable function objectsIn general, a function object has restrictions on the type of its argument. The type restrictions need not be simple, though: Adaptable function objects are important, because they can be used by function object adaptors: function objects that transform or manipulate other function objects. The C++ Standard Library provides many different function object adaptors, including Predefined function objectsThe C++ Standard Library includes in the header file ExamplesFunction wrappers can be used to make calls to ordinary functions or to functions objects created by lambda expressions. import std;
// Define a template function
template <typename T>
void printValue(T value) {
std::println("{}", value);
}
int main(int argc, char* argv[]) {
// A function wrapper to a function
std::function<void(int)> func_a = printValue<int>;
func_a(2015);
// A function wrapper to a function pointer
std::function<void(int)> func_b = &printValue<int>;
func_b(2016);
// A function wrapper to a lambda function.
std::function<void(int)> func_c = [](int value) -> void {
std::println("{}", value);
};
func_c(2017);
/* A function wrapper generated by std::bind().
* Pass a pre-defined parameter when binding.
*/
std::function<void(void)> func_d = std::bind(printValue<std::string>, "PI is");
func_d();
/* A function wrapper generated by std::bind().
* Pass a parameter when calling the function.
*/
std::function<void(float)> func_e = std::bind(printValue<float>, std::placeholders::_1);
func_e(3.14159);
}
Function wrappers also can be used to access member variables and member functions of classes. import std;
template <typename T>
class AnyData {
public:
T value;
AnyData(T value):
value{value} {}
void print() {
std::println("{}", value);
}
void printAfterAdd(T value) {
std::println("{}", this->value + value);
}
};
int main(int argc, char* argv[]) {
// A function wrapper to a member variable of a class
AnyData<int> data_a{2016};
std::function<int(AnyData<int> &)> func_a = &AnyData<int>::value;
std::println("{}", func_a(data_a));
// A function wrapper to member function without parameter passing
AnyData<float> data_b{2016.1};
std::function<void(AnyData<float>&)> func_b = &AnyData<float>::print;
func_b(data_b);
// A function wrapper to member function with passing a parameter
std::function<void(AnyData<float>&, float)> func_c = &AnyData<float>::printAfterAdd;
func_c(data_b, 0.1);
// A function wrapper to member function generated by std::bind
std::function<void(float)> func_d = std::bind(
&CAnyData<float>::printAfterAdd,
&data_b,
std::placeholders::_1
);
func_d(0.2);
}
References
External links |