title: Calling a stateless lambda without an instance (only type)
body: <p>I'm trying to write a wrapper for a <a href="http://orx-project.org/orx/doc/html/group__orx_command.html#gaabb6d028ab52dffb1c9bbfe3e75b9601" rel="nofollow">"register callback" type of interface</a> from a C library. The issue is quite complicated by the fact that, the library lets you register "variadic" functions by accepting a list of parameter definitions. Then at callback time, the function is expected to extract its arguments from a type-erased list of arguments. Good old C...</p>
  
  <p>The interface I'm trying to create is to accept any function, even a lambda, and automatically generate all the machinery to correctly register this function, along with registering the arguments and extracting them during callback time. So the user should only have to type:</p>
  
  <pre><code>register_callback("Callback Name", [](int i){return i+0.5;});
  </code></pre>
  
  <p>Now this is theoretically possible, but at one point, I need to be able to call the lambda without any instance, but with access to only its type. I don't understand why, but the default constructor of a stateless (non-capturing) lambda is deleted, so I can't simply default-construct from its type. What I'm planning to do instead is a very dirty-looking, but should probably be OK way to work around this:</p>
  
  <pre><code>template &lt;class Func, class RET, class ...ARGS&gt;
  struct from_stateless {
      static RET to_function(ARGS...args) {
          RET (*f)(ARGS...) = *(Func *)(0);
          return f(args...);
      }
  };
  </code></pre>
  
  <p>so that <code>from_stateless&lt;LAMBDA_TYPE, RET, ARGS...&gt;::to_function</code> is actually a function pointer that I can call without an argument and more importantly one that I can pass as a TEMPLATE ARGUMENT.</p>
  
  <p>Under normal circumstances, the line <code>RET (*f)(ARGS...) = *(Func *)(0);</code> would be suicide, but it really should be safe with this use case, isn't it? After all, the function pointer obtained after conversion couldn't in any universe possibly depend on the lambda instance.</p>
  
  <p>So, the question is, is it safe to do this as long as I make sure that the type is indeed a stateless lambda? Or am I missing something? Note that the <code>RET (*f)(ARGS...) = *(Func *)(0);</code> would trigger a compiler error if a closure accidentally slips through.</p>
  
  <p>CLARIFICATION: I can't just decay the lambda to a function pointer and register it, since the signature of the lambda is not compatible with the "Register" method. The register method expects a function with signature: <code>void (*)(int number_of_args, TypeErasedValue * arguments, TypeErasedValue * result)</code> So you see, I need to (and already do), through template metaprograming, generate a free function templated on the type of the lambda to act as an adaptor between the expected and the actual signatures.</p>