[英]std::bind with variadic template and auto return type
按照這個問題中的代碼,我有一個帶可變參數模板函數的std::bind
。 如果我嘗試提供具有auto
返回功能的模板,gcc會拒絕該程序:
#include <functional>
template <typename... Args
auto inv_impl(Args... a) { return (a + ...); }
template <typename... Args>
auto inv(Args... args) {
auto bound = std::bind(&inv_impl<Args...>, args...);
return bound;
}
int main() {
auto b = inv(1, 2);
}
編譯錯誤是:
foo.cc: In instantiation of ‘auto inv(Args ...) [with Args = {int, int}]’:
foo.cc:41:30: required from here
foo.cc:36:25: error: no matching function for call to ‘bind(<unresolved overloaded function type>, int&, int& ’
auto bound = std::bind(&inv_impl<Args...>, args...);
~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from foo.cc:2:
/usr/include/c++/8.1.1/functional:808: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++/8.1.1/functional:808:5: note: template argument deduction/substitution failed:
foo.cc:36:25: note: couldn't deduce template parameter ‘_Func’
auto bound = std::bind(&inv_impl<Args...>, args...);
~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from foo.cc:2:
/usr/include/c++/8.1.1/functional:832: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++/8.1.1/functional:832:5: note: template argument deduction/substitution failed:
foo.cc:36:25: note: couldn't deduce template parameter ‘_Result’
auto bound = std::bind(&inv_impl<Args...>, args...);
~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
foo.cc:37:10: error: unable to deduce ‘auto’ from ‘bound’
return bound;
^~~~~
foo.cc: In function ‘int main()’:
foo.cc:41:8: error: ‘void b’ has incomplete type
auto b = inv<int, int>(1, 2);
^
據我所知,由我工作拼寫的返回類型,它只是編譯器無法處理的auto
返回類型。
有沒有辦法在不知道代碼寫入時返回類型的情況下從inv_impl返回? (我正在使用declval
/ decltype
結構,但我想知道是否有更好的東西)
這絕對是一個gcc bug(提交86826 )。
解決方案是......不要使用std::bind()
。 無論如何,幾乎沒有理由。 Lambdas嚴格優越:
template <typename... Args>
auto inv(Args... args) {
return [=]{ return inv_impl(args...); };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.