[英]template argument type deduction from std::function return type with lambda
[英]How to auto deduct argument and return type of lambda with std::function?
這段代碼:
template<typename Arg, typename Ret>
Ret fun(std::function<Ret(Arg)> fun){
Arg x=0;
return fun(x);
};
auto f=[](int x){return x;};
fun(f); //compilation failed.
不起作用。 我想在fun
中獲取 lambda 的參數和返回類型。
我認為參數類型在編譯時已經知道,為什么編譯器不能自動扣除它?
The problem here is that the lambda is not an std::function
, so you're asking the compiler to do a deduction (find the type of Arg
AND Ret
) and a convertion ie convert the lambda to an std::function
. 這種組合會導致沖突。
如果您仍想使用std::function
作為fun
的參數類型,那么更容易做的事情是創建一個實用程序來識別std::function
將您的可調用對象轉換為,例如:
#include <functional>
using namespace std;
template<typename T>
struct memfun_type
{
using type = void;
};
template<typename Ret, typename Class, typename... Args>
struct memfun_type<Ret(Class::*)(Args...) const>
{
using type = std::function<Ret(Args...)>;
};
template<typename F>
typename memfun_type<decltype(&std::decay_t<F>::operator())>::type
function_from(F&& func)
{
return std::forward<F>(func);
}
您將用作
fun(function_from(f)); // Auto-detect <Ret(Args...)> types.
在展示了自動檢測的工作原理之后,請注意,從 C++17 開始,CTAD 功能可以為您完成這項工作。 所以在較新的編譯器中這也有效:
fun(std::function(f)); // Again no types specified.
或者,您可以使您的f
更通用一點,只使用參數推導,例如:
template <class F>
auto fun(F &&fun)
{
int x=0;
return std::invoke(std::forward<F>(fun), x);
};
fun(f); // Call directly with your lambda
使用 c++20 概念,此版本可以限制為您想要的參數和輸入 function 類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.