[英]Template Type Deduction with Lambdas
我面臨的問題很簡單。 給出以下代碼:
template <typename ReturnType, typename... Args>
auto CallIt( ReturnType( *method )( Args... ) )
{
return method;
}
auto test = CallIt( [] ( int a, int b )
{
return a > b;
} );
我得到的錯誤(使用VS13與2013年11月的CTP編譯器)是:
Could not deduce template argument for ReturnType (__cdecl *)(Args...) from main::<lambda_e795bf5a030334e5fc8f3c26dbe00e0e>
我知道lambda不是函數指針,但是不捕獲的lambda可以分配給匹配簽名的函數指針。 如果您明確指定模板參數,則此方法有效。 我希望看到一種方法可以在不必明確指定模板參數的情況下工作。 預先感謝您的幫助。
正如Marco A.提供的答案的評論中所指出的,可能有一個解決方案,使用lambda類上的一元+運算符,有效地將其轉換為函數指針。 但是,在請求的IDE /編譯器組合中,我收到以下警告轉為錯誤:
從“lambda [] bool(int a,int b) - > bool”到內置類型的多個轉換函數適用:
function“lambda [] bool(int a,int b) - > bool :: operator bool(*)(int a,int b)()const”
function“lambda [] bool(int a,int b) - > bool :: operator bool(*)(int a,int b)()const”
function“lambda [] bool(int a,int b) - > bool :: operator bool(*)(int a,int b)()const”
function“lambda [] bool(int a,int b) - > bool :: operator bool(*)(int a,int b)()const”
這個intellisense錯誤揭示了生成的編譯錯誤,指定:
錯誤C2593:'operator +'不明確
1)添加適當的尾隨返回類型
2)如果你想傳遞一個函數指針,讓lambda 符合那個
template <typename ReturnType, typename... Args>
auto CallIt( ReturnType( *method )( Args... ) ) -> ReturnType(*)(Args...)
{
return method;
}
auto test = CallIt( +[] ( int a, int b )
{
return a > b;
} );
編輯:似乎MSVC2013出現了問題。 作為一種解決方法,您可以嘗試以下方法暫時有效:
#include <iostream>
#include <functional>
using namespace std;
template <typename ReturnType, typename... Args>
auto CallIt( std::function<ReturnType( Args... )> method ) -> std::function<ReturnType( Args... )>
{
return method;
}
int main() {
std::function<bool(int,int)> lambda = [] ( int a, int b ) { return a > b; };
auto test = CallIt( lambda );
cout << test(4,1);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.