我有一个简单的模板函数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>,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,_BoundArgs>::type std::bind(_Func&&,_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可以编译,没有任何错误.
所以我的问题是:有没有办法在这种情况下指定模板函数的预期返回值?
@H_502_14@解决方法
看起来编译器不确定do_something< int>的类型. – 我不确定这是编译器问题还是语言问题 – 但你可以强制编译器通过使用do_something< int>来调整其类型.以前相对琐碎的方式.例如,下面用gcc和clang trunk版本编译好(根据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,12); function(); return 0; }@H_502_14@ @H_502_14@ 原文链接:https://www.f2er.com/c/118482.html