GCC无法从模板函数推导出自动返回类型?

时间:2016-07-04 00:09:34

标签: c++ templates gcc type-deduction

我有一个简单的模板函数 do_something ,它返回一个整数: 123

template<typename T>
auto do_something(T input) {
  std::this_thread::sleep_for(std::chrono::seconds(1));
  return 123;
}

int main(int argc, char *argv[]) {
  std::function<int(void)> function = std::bind(do_something<int>, 12);
  function();
  return 0;
}

使用GCC 6.1.1,我收到此错误:

test.cpp: In function ‘int main(int, char**)’:
test.cpp:16:70: error: no matching function for call to ‘bind(<unresolved overloaded function type>, int)’
   std::function<int(void)> function = std::bind(do_something<int>, 12);
                                                                      ^
In file included from /usr/include/c++/6.1.1/thread:39:0,
                 from test.cpp:4:
/usr/include/c++/6.1.1/functional:1331:5: note: candidate: template<class _Func, class ... _BoundArgs> typename std::_Bind_helper<std::__is_socketlike<_Func>::value, _Func, _BoundArgs ...>::type std::bind(_Func&&, _BoundArgs&& ...)
     bind(_Func&& __f, _BoundArgs&&... __args)
     ^~~~
/usr/include/c++/6.1.1/functional:1331:5: note:   template argument deduction/substitution failed:
test.cpp:16:70: note:   couldn't deduce template parameter ‘_Func’
   std::function<int(void)> function = std::bind(do_something<int>, 12);
                                                                      ^
In file included from /usr/include/c++/6.1.1/thread:39:0,
                 from test.cpp:4:
/usr/include/c++/6.1.1/functional:1359:5: note: candidate: template<class _Result, class _Func, class ... _BoundArgs> typename std::_Bindres_helper<_Result, _Func, _BoundArgs>::type std::bind(_Func&&, _BoundArgs&& ...)
     bind(_Func&& __f, _BoundArgs&&... __args)
     ^~~~
/usr/include/c++/6.1.1/functional:1359:5: note:   template argument deduction/substitution failed:
test.cpp:16:70: note:   couldn't deduce template parameter ‘_Result’
   std::function<int(void)> function = std::bind(do_something<int>, 12);

如您所见,编译器无法推断出函数的结果类型。

请注意:clang ++ 3.8.0可以编译,没有任何错误。

所以我的问题是:有没有办法在这种情况下从模板函数中指定预期的返回值?

1 个答案:

答案 0 :(得分:0)

看起来编译器不确定do_something<int>的类型-我不确定这是编译器问题还是语言问题-但您可以强制编译器获取其通过使用do_something<int>进行排序的方式比较简单。例如,以下代码可以同时使用gcc和clang主干版本(根据godbolt)进行编译。

#include <functional>

template<typename T>
auto do_something(T input) {
  return 123;
}

// Make the compiler workout the type of do_something<int> so we can use it later.
auto f = do_something<int>;

int main(int argc, char *argv[]) {
  std::function<int(void)> function = std::bind(do_something<int>, 12);
  function();
  return 0;
}