Callbacks and their Various Uses in C
In C , a callback is a callable (discussed later) accepted by a class or function, employed to customize current logic based on the provided callback.
Reasons for Using Callbacks:
What are Callables in C ?
Writing and Calling Callbacks:
Function Pointers:
Pointer to Member Function:
std::function Objects:
Examples Using std::function:
Generalizing Code:
template<class R, class T> void stdf_transform_every_int_templ(int *v, unsigned const n, std::function<R(T)> fp) { for (unsigned i = 0; i < n; ++i) { v[i] = fp(v[i]); } }
Templated Callbacks:
template<class F> void transform_every_int_templ(int *v, unsigned const n, F f) { for (unsigned i = 0; i < n; ++i) { v[i] = f(v[i]); } }
Type-Name Implementation:
template <class T> std::string type_name() { typedef typename std::remove_reference<T>::type TR; std::unique_ptr<char, void(*)(void*)> own (abi::__cxa_demangle(typeid(TR).name(), nullptr, nullptr, nullptr), std::free); std::string r = own != nullptr?own.get():typeid(TR).name(); if (std::is_const<TR>::value) r += " const"; if (std::is_volatile<TR>::value) r += " volatile"; if (std::is_lvalue_reference<T>::value) r += " &&"; else if (std::is_rvalue_reference<T>::value) r += " &&"; return r; }
The above is the detailed content of How Do Callbacks Work in C , and What Are Their Various Uses?. For more information, please follow other related articles on the PHP Chinese website!