【发布时间】:2016-11-05 15:18:06
【问题描述】:
我有一个简单的模板函数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 可以编译没有任何错误。
所以我的问题是:有没有办法像在这种情况下从模板函数中指定预期的返回值?
【问题讨论】:
-
如果尾随返回类型取决于您的参数参数之一。
-
您使用了哪些编译器标志?你试过
-std=c++14吗? -
显然我已经用标志 -std=c++14 编译了
-
@BiagioFesta 我在一段时间后在这里阅读关于 SO 的问题时发现,似乎很少“明显”;)
-
gcc 将编译以下内容:
auto f=do_something<int>; std::function<int(void)> function = std::bind(f, 12);。但是,我没有足够的language-lawyer-fu 来权威地说明这是否是 gcc 错误,或者这些多米诺骨牌是如何倒下的,就 C++ 规范而言。
标签: c++ templates gcc type-deduction