Why can’t I define a function inside another function?

It is not obvious why one is not allowed; nested functions were proposed a long time ago in N0295 which says: We discuss the introduction of nested functions into C++. Nested functions are well understood and their introduction requires little effort from either compiler vendors, programmers, or the committee. Nested functions offer significant advantages, […] … Read more

Why are Promises Monads?

UDATE. See this new library providing functor and monad operators for plain callback-based functions that do not have the issues with theneables: https://github.com/dmitriz/cpsfy The JS Promise is neither a Functor nor an Applicative nor a Monad It is not a functor, because the composition preservation law (sending compositions of functions to compositions of their images) … Read more

Why use functors over functions?

At least four good reasons: Separation of concerns In your particular example, the functor-based approach has the advantage of separating the iteration logic from the average-calculation logic. So you can use your functor in other situations (think about all the other algorithms in the STL), and you can use other functors with for_each. Parameterisation You … Read more

How do I get the argument types of a function pointer in a variadic template class?

You can write function_traits class as shown below, to discover the argument types, return type, and number of arguments: template<typename T> struct function_traits; template<typename R, typename …Args> struct function_traits<std::function<R(Args…)>> { static const size_t nargs = sizeof…(Args); typedef R result_type; template <size_t i> struct arg { typedef typename std::tuple_element<i, std::tuple<Args…>>::type type; }; }; Test code: struct … Read more