Chr*_*Vig 4 c++ lambda variadic-templates generic-lambda c++14
我正在尝试编写一个函数,该函数将返回带有可变参数的泛型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);
};
}
Run Code Online (Sandbox Code Playgroud)
我不确定在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);
};
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但返回的lambda不是通用的 - 它不适用于任何任意参数包.
小智 8
您可以通过简单地使用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);
};
}
Run Code Online (Sandbox Code Playgroud)
我不确定在std :: tuple模板参数中放什么.我已经尝试过decltype(args),decltype(args ...),auto,auto ......等等,但我一直遇到编译器错误.
试试吧
std::tuple<decltype(args)...>
Run Code Online (Sandbox Code Playgroud)
功能齐全
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);
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
637 次 |
| 最近记录: |