Overload resolution with std::function

In C++11… Let’s take a look at the specification of the constructor template of std::function (which takes any Callable): [func.wrap.func.con]/7-10 template<class F> function(F f); template <class F, class A> function(allocator_arg_t, const A& a, F f); 7 Requires: F shall be CopyConstructible. f shall be Callable (20.10.11.2) for argument types ArgTypes and return type R. The … Read more

Scala single method interface implementation

Scala has experimental support for SAMs starting with 2.11, under the flag -Xexperimental: Welcome to Scala version 2.11.0-RC3 (OpenJDK 64-Bit Server VM, Java 1.7.0_51). Type in expressions to have them evaluated. Type :help for more information. scala> :set -Xexperimental scala> val r: Runnable = () => println(“hello world”) r: Runnable = $anonfun$1@7861ff33 scala> new Thread(r).run … Read more

Using Boost adaptors with C++11 lambdas

http://smellegantcode.wordpress.com/2011/10/31/linq-to-c-or-something-much-better/ But you can use this, that works well. #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> #include <vector> #include <functional> int main() { std::vector<int> v{ 1,5,4,2,8,5,3,7,9 }; std::function<int(int)> func = [](int i) { return -i; }; std::cout << *boost::min_element(v | boost::adaptors::transformed( func)) << std::endl; return 0; } http://liveworkspace.org/code/b78b3f7d05049515ac207e0c12054c70 #define BOOST_RESULT_OF_USE_DECLTYPE works fine in VS2012 for example.

Convert DataTable to Generic List in C#

You could actually shorten it down considerably. You can think of the Select() extension method as a type converter. The conversion could then be written as this: List<Cards> target = dt.AsEnumerable() .Select(row => new Cards { // assuming column 0’s type is Nullable<long> CardID = row.Field<long?>(0).GetValueOrDefault(), CardName = String.IsNullOrEmpty(row.Field<string>(1)) ? “not found” : row.Field<string>(1), }).ToList();

How to convert Func to Predicate?

Easy: Func<string,bool> func = x => x.Length > 5; Predicate<string> predicate = new Predicate<string>(func); Basically you can create a new delegate instance with any compatible existing instance. This also supports variance (co- and contra-): Action<object> actOnObject = x => Console.WriteLine(x); Action<string> actOnString = new Action<string>(actOnObject); Func<string> returnsString = () => “hi”; Func<object> returnsObject = new … Read more

When to use functors over lambdas

A lambda is a functor – just defined with a shorter syntax. The problem is that this syntax is limited. It doesn’t always allow you to solve a problem in the most efficient and flexible way – or at all. Until C++14, the operator() couldn’t even be a template. Furthermore, a lambda has exactly one … Read more