4

我正在尝试编写一个函数,该函数将返回带有可变参数的通用 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);
    };
}

这工作正常,但返回的 lambda 不是通用的 - 它不适用于任何任意参数包。

4

2 回答 2

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);
    };
}
于 2017-01-03T02:36:53.140 回答
6

我不确定在 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);
    };
}
于 2017-01-03T02:30:32.807 回答