Empirical
GenericFunction.h
Go to the documentation of this file.
1 
15 #ifndef EMP_GENERIC_FUNCTION_H
16 #define EMP_GENERIC_FUNCTION_H
17 
18 #include <functional>
19 #include "../base/assert.h"
20 
21 namespace emp {
22 
28 
30  protected:
31  public:
32  virtual ~GenericFunction() { ; }
33 
35  template <typename RETURN, typename... Ts> auto Call(Ts &&... args);
36 
38  template <typename RETURN, typename... Ts> auto operator()(Ts &&... args) {
39  return Call<RETURN, Ts...>( std::forward<Ts>(args)... );
40  }
41 
43  template <typename T> auto Convert();
44  };
45 
46  // Undefined base type for Function, to create an error if a function type is not passed in.
47  template <typename... Ts> class Function;
48 
49  // Specialized form for proper function types.
50  template <typename RETURN, typename... PARAMS>
51  class Function<RETURN(PARAMS...)> : public GenericFunction {
52  protected:
53  std::function<RETURN(PARAMS...)> fun;
54  public:
56  template <typename... Ts>
57  Function(Ts &&... args) : fun(std::forward<Ts>(args)...) { ; }
58 
60  template <typename... Ts>
61  RETURN Call(Ts &&... args) { return fun(std::forward<Ts>(args)...); }
62 
64  template <typename... Ts>
65  RETURN operator()(Ts &&... args) { return fun(std::forward<Ts>(args)...); }
66  };
67 
68  template <typename RETURN, typename... Ts>
69  auto GenericFunction::Call(Ts &&... args) {
70  using fun_t = Function<RETURN(Ts...)>;
71 
72  emp_assert(dynamic_cast<fun_t *>(this)); // Make sure this Call cast is legal.
73 
74  fun_t * fun = (fun_t *) this;
75  return fun->Call( std::forward<Ts>(args)... );
76  }
77 
78  template <typename T> auto GenericFunction::Convert() {
79  emp_assert(dynamic_cast<Function<T> *>(this));
80  return (Function<T> *) this;
81  }
82 
83 }
84 
85 #endif
RETURN operator()(Ts &&...args)
Forward all args to std::function call.
Definition: GenericFunction.h:65
Definition: BitVector.h:785
auto Call(Ts &&...args)
A generic form of the function call operator; use arg types to determine derived form.
Definition: GenericFunction.h:69
Definition: GenericFunction.h:29
std::function< RETURN(PARAMS...)> fun
Definition: GenericFunction.h:53
virtual ~GenericFunction()
Definition: GenericFunction.h:32
auto operator()(Ts &&...args)
A generic form of the function call operator; use arg types to determine derived form.
Definition: GenericFunction.h:38
If we are in emscripten, make sure to include the header.
Definition: array.h:37
Function(Ts &&...args)
The std::function to be called.
Definition: GenericFunction.h:57
Definition: GenericFunction.h:47
#define emp_assert(...)
Definition: assert.h:199
auto Convert()
Convert this GenericFunction into a derived emp::Function.
Definition: GenericFunction.h:78
RETURN Call(Ts &&...args)
Forward all args to std::function call.
Definition: GenericFunction.h:61