From: ulrich.eckhardt@dominolaser.com   
      
   Am 13.06.2012 20:48, schrieb Jens Auer:   
   > I am trying to write a little helper template function which takes a   
   > std::function object and a parameter and calls the function object and   
   > does some additional work. This all works fine until I try to call the   
   > template function with a function pointer directly without first   
   > creating a temporary std::function object:   
      
   Why do you need a std::function object in the first place? The point is   
   that...   
      
   > template   
   > void call(std::function func, T x)   
   > {   
   > A a;   
   > func(&a,x);   
   > }   
      
   ...could be written like this:   
      
    template   
    void call(function_type f, parameter_type p)   
    {   
    A a;   
    f(&a, p);   
    }   
      
   This is similar to algorithms from the STL that take a functor for   
   ordering or comparison. They also only need that the thing can be called   
   like a function but not that it is some specific type.   
      
      
   [...]   
   > template argument deduction/substitution failed: mismatched types   
   > 'std::function' and 'void (*)(int)'   
   [...]   
   > The problems seems to be that the compiler cannot figure out the the   
   > template has to be instantiated with T=int, but I wonder why that is.   
      
   There are two parameters of the function which are used in deducing the   
   type of T. The second one gives an obvious 'int' as answer. The first   
   one however is not so clear, because the given type (function pointer)   
   is not actually the one in the function declaration (std::function).   
   Instead, it first requires a conversion to the argument type. However,   
   in order to perform that conversion, you first need to know the argument   
   type, which again depends on the template parameters. In other words,   
   you have a chicken-and-egg problem here, which is where compiler simply   
   bails out and refuses to guess.   
      
   Notes here:   
   1. If you have two dependent parameters, both have to yield the same   
   answer, the compiler won't use just one of them.   
   2. In theory, std::function could have a specialization for 'void(int)'   
   that is not an acceptable conversion for such a pointer. This means that   
   the compiler also can't guess that this is the right conversion.   
      
   If you give the type explicitly, it works. Similarly if you use the   
   version suggested above with two template parameters.   
      
   Good luck!   
      
   Uli   
      
      
   --   
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
    [ comp.lang.c++.moderated. First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|