Deduce template argument from std::function call signature

北慕城南 提交于 2019-12-17 05:11:21

问题


Consider this template function:

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

Why isn't it possible for the compiler to deduce ReturnT from the passed call signature?

bool bar() { /* ... */ }

foo<bool>(bar); // works
foo(bar); // error: no matching function call

回答1:


std::function<bool()> bar;

foo(bar); // works just fine

C++ can't deduce the return type from your function bar because it would have to know the type before it could find all the constructors that take your function pointer.

For example, who's to say that std::function<std::string()> doesn't have a constructor taking a bool (*)()?




回答2:


A function pointer of type bool (*)() can be converted to std::function<bool()> 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<bool()> 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<void()> or std::function<int()> ... which should be deduced?

Consider this simplification:

template<typename T>
  struct function
  {
    template<typename U>
      function(U) { }
  };

template<typename T>
  void foo(function<T>)
  { }

int main()
{
    foo(1);
}

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




回答3:


The function bar is of type bool (*)() or so, that is: a normal pre-C++11 function type. I'm not that confident in C++11, but I guess the compiler does not see the connection between bool (*)() and const std::function<ReturnT()>&, even when the first can be implicitly converted into the second for ReturnT = bool.



来源:https://stackoverflow.com/questions/11103384/deduce-template-argument-from-stdfunction-call-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!