2017-01-03 39 views
4

我想寫一個函數,將返回一個generic lambda與可變參數,其中lambda檢查其中一個參數是否等於一個特定的值。這裏是(大約)我想要做的事:如何從泛型lambda的可變參數包中獲取類型?

template <int Index, typename TValue> 
inline auto arg_eq(const TValue& value) 
{ 
    return [value] (auto... args) -> bool { 
     return (std::get<Index>(std::tuple</* ??? */>(args...)) == value); 
    }; 
} 

我不知道要放什麼東西在std::tuple</* ??? */>模板參數。我試過decltype(args),decltype(args...),auto,auto...,和其他一些事情,但我不斷收到編譯器錯誤。這甚至有可能嗎?

非仿製藥會是這樣的:

template <int Index, typename TValue, typename... TArgs> 
inline auto arg_eq(const TValue& value) 
{ 
    return [value] (TArgs... args) -> bool { 
     return (std::get<Index>(std::tuple<TArgs...>(args...)) == value); 
    }; 
} 

這工作正常,但返回的拉姆達不是通用的 - 它不與任意參數包工作。

回答

5

我不知道該怎麼把std :: tuple模板參數。我嘗試了decltype(args),decltype(args ...),auto,auto ...和其他一些東西,但是我不斷收到編譯器錯誤。

嘗試

std::tuple<decltype(args)...> 

全功能

template <int Index, typename TValue> 
inline auto arg_eq(const TValue& value) 
{ 
    return [value] (auto... args) -> bool { 
     return (std::get<Index>(std::tuple<decltype(args)...>(args...)) 
       == value); 
    }; 
} 
7

您可避免通過簡單地使用std::make_tuple提類型:

template <int Index, typename TValue> 
auto arg_eq(const TValue& value) 
{ 
    return [value] (auto... args) -> bool { 
     return (std::get<Index>(std::make_tuple(args...)) == value); 
    }; 
} 
+2

或'的std :: tie'。 .. – Jarod42

相關問題