title: Access to templated lambda from std::function in C++
body: <p>I'm trying to add some instrumentation to my lambda in order to store some data (ie when the lambda has been triggered) but I'm having some trouble to retrieve a lambda from an std::function.
  I have created a generic functor in order to store any lambda and my parameters and then I store this functor into an std::function.</p>
  
  <p>When I try to access to my functor from the std::function, the type passed through the target method is not working... The type I passed doesn't seems to be the good one and I don't know how to pass the lambda type which is not a type by definition...</p>
  
  <p>Could anyone help me on how to achieve that ?
  I'm using Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27030.1 for x64</p>
  
  <p>Thanks</p>
  
  <p>Here is an example:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;functional&gt;
  #include &lt;string&gt;
  
  template &lt;typename Signature&gt;
  class lambda_wrapper
  {
      public:
      lambda_wrapper(Signature&amp;&amp; lambda, const std::string&amp; iName)
          : _lambda(std::move(lambda))
          , _sName(iName)
      {}
  
      template &lt;typename... Args&gt; inline
          auto operator()(Args&amp;&amp;... args)
      {
          return _lambda(std::forward&lt;decltype(args)&gt;(args)...);
      }
  
      std::string&amp; getName()
      {
          return _sName;
      }
      private:
      Signature _lambda;
      std::string _sName;
  };
  
  template &lt;typename Signature&gt;
  lambda_wrapper&lt;Signature&gt; myLambda(Signature&amp;&amp; lambda, const std::string&amp; iName)
  {
      return {std::forward&lt;Signature&gt;(lambda), iName};
  }
  
  class MyClass
  {
      public:
      MyClass()
          : _lambda(myLambda([](int)
      {}, "test"))
      {
  
      }
      virtual ~MyClass() = default;
  
      void printVal()
      {
          lambda_wrapper&lt;std::function&lt;void(int)&gt;&gt;* pWrapper = _lambda.target&lt;lambda_wrapper&lt;std::function&lt;void(int)&gt;&gt;&gt;();
          if (pWrapper)
              std::cout &lt;&lt; pWrapper-&gt;getName();
          else
              std::cout &lt;&lt; "NULL" &lt;&lt; std::endl;
  
          std::cout &lt;&lt; "Stored type name=" &lt;&lt; _lambda.target_type().name() &lt;&lt; std::endl;
          std::cout &lt;&lt; "Cast type name=" &lt;&lt; typeid(lambda_wrapper&lt;std::function&lt;void(int)&gt;&gt;).name() &lt;&lt; std::endl;
      }
  
      private:
      std::function&lt;void(int)&gt; _lambda;
  };
  
  int main()
  {
      MyClass myClass;
      myClass.printVal();
  }
  </code></pre>
  
  <p>and here is the result:</p>
  
  <pre><code>NULL
  Stored type name=class lambda_wrapper&lt;class &lt;lambda_de654b4bbc7b5fec872744c55537b509&gt; &gt;
  Cast type name=class lambda_wrapper&lt;class std::function&lt;void __cdecl(int)&gt; &gt;
  </code></pre>