Deduce template argument from std::function call signature

前端 未结 3 1126
北荒
北荒 2020-11-27 22:10

Consider this template function:

template
ReturnT foo(const std::function& fun)
{
    return fun();
}
         


        
3条回答
  •  -上瘾入骨i
    2020-11-27 22:51

    A function pointer of type bool (*)() can be converted to std::function but is not the same type, so a conversion is needed. Before the compiler can check whether that conversion is possible it needs to deduce ReturnT as bool, but to do that it needs to already know that std::function is a possible conversion, which isn't possible until it deduces ReturnT ... see the problem?

    Also, consider that bool(*)() could also be converted to std::function or std::function ... which should be deduced?

    Consider this simplification:

    template
      struct function
      {
        template
          function(U) { }
      };
    
    template
      void foo(function)
      { }
    
    int main()
    {
        foo(1);
    }
    

    How can the compiler know whether you wanted to create function or function or function when they can all be constructed from an int?

提交回复
热议问题