Vita
ga/evaluator.tcc
1/**
2 * \file
3 * \remark This file is part of VITA.
4 *
5 * \copyright Copyright (C) 2014-2017 EOS di Manlio Morini.
6 *
7 * \license
8 * This Source Code Form is subject to the terms of the Mozilla Public
9 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
10 * You can obtain one at http://mozilla.org/MPL/2.0/
11 */
12
13#if !defined(VITA_GA_EVALUATOR_H)
14# error "Don't include this file directly, include the specific .h instead"
15#endif
16
17#if !defined(VITA_GA_EVALUATOR_TCC)
18#define VITA_GA_EVALUATOR_TCC
19
20///
21/// GP-evaluators use datasets, GA-evaluators need functions to be maximized.
22///
23/// \param[in] f an objective function
24///
25template<class T, class F>
26ga_evaluator<T, F>::ga_evaluator(F f) : f_(f)
27{
28 // The assertion `assert(f)` works with function pointers and non capturing
29 // lambdas (which are implicitly convertible to function pointers) but
30 // fails with capturing lambdas
31 // (e.g. <http://stackoverflow.com/q/7852101/3235496>).
32}
33
34///
35/// \param[in] f objective function
36/// \return an evaluator based on `f`
37///
38/// This is the so called object generator idiom. Here it's used because C++11
39/// standard doesn't allow for template argument deduction from the parameters
40/// passed to the constructor.
41///
42/// Any reasonable compiler will optimize away the temporary object and this
43/// is usually faster than a solution based on `std::function`.
44///
45/// \see
46/// * <http://stackoverflow.com/q/984394/3235496>
47/// * <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3602.html>
48///
49template<class T, class F>
50ga_evaluator<T, F> make_ga_evaluator(F f)
51{
52 return ga_evaluator<T, F>(f);
53}
54
55///
56/// \return the fitness of the individual
57///
58template<class T, class F>
59fitness_t ga_evaluator<T, F>::operator()(const T &ind)
60{
61 const auto f_v(f_(ind));
62
63 using std::isfinite;
64 if (isfinite(f_v))
65 return {f_v};
66
67 return {};
68}
69#endif // include guard