简体   繁体   English

如何在条件下展开可变参数模板?

[英]How Do I Unroll a Variadic Template in a Condition?

I'm looking to unroll a variadic template into separate functions used in the conjunction of an if -statement. 我希望将可变参数模板展开为与if -statement结合使用的单独函数。 Here's an example of what I'm trying to do: 这是我要执行的操作的一个示例:

template <typename T, size_t I>
bool bar(const T& param) { return param[I] != 13; }

template <typename T, size_t... ARGS>
void bar(const T& param, const std::index_sequence<ARGS...>&) { 
    if(bar<ARGS>(param) && ...)
    {
        cout << "no matches\n";
    }
    else
    {
        cout << "matched\n";
    }
}

But this gives me the error: 但这给了我错误:

error C3520: ARGS : parameter pack must be expanded in this context 错误C3520: ARGS :必须在这种情况下扩展参数包

I want the line: if(bar<ARGS>(param) && ...) to unroll to: if(bar<0U>(param) && bar<1U>(param) && bar<2U>(param)) Is there a way I can do this? 我想要这行: if(bar<ARGS>(param) && ...)展开到: if(bar<0U>(param) && bar<1U>(param) && bar<2U>(param))是有办法可以做到吗? Or is there an additional adapter that I can use which will accomplish this? 还是有一个我可以使用的附加适配器来完成此任务?

Live Example 现场例子

If your compiler supports C++17's fold-expressions you need to change two things to make it work: 如果您的编译器支持C ++ 17的fold-expressions ,则需要更改两项以使其起作用:

1.Change the order of template parameters in bar so that T can be deduced when I in explicitly specified: 1.更改bar中模板参数的顺序,以便在明确指定I时可以推导出T

template <size_t I, typename T>
bool bar(const T& param) { return param[I] != 13; }

2.Add a pair of parentheses inside if since they are a mandatory part of a fold-expression: 2. if在折叠表达式中必须加上括号,请在其中加上一对括号:

if ((bar<ARGS>(param) && ...))

Live Example 现场例子

You need an additional couple of parentheses 您需要再加上几个括号

// .V.......................V
if( (bar<ARGS>(param) && ...) )

Obviously if your compiler support C++17 (template folding). 显然,如果您的编译器支持C ++ 17(模板折叠)。

Maybe clearer as follows 也许更清楚如下

if( true == (bar<ARGS>(param) && ...) )

So in the sad event that mine does not [support fold expressions] ... Can I do anything? 因此,在不幸的情况下,我的人不[支持折叠表达式] ...我可以做什么?

Well, if that's really the case and the issue was not solely for forgetting the required parentheses , then you can go the way variadic templates needed to be handled before C++17: 好吧,如果确实是这样,并且问题不仅仅在于忘记必需的括号 ,那么您可以采用在C ++ 17之前需要处理可变参数模板的方式:

template < typename T >
bool bar(T const& param) { return true; }

template <typename T, size_t I, size_t ... II>
bool bar(T const& param) { return param[I] != 13 && bar<T, II...>(param); }

template <typename T, size_t... ARGS>
void bar(T const& param, std::index_sequence<ARGS...> const&)
{
    if(bar<T, ARGS...>(param))
    {
        std::cout << "no matches\n";
    }
    else
    {
        std::cout << "matched\n";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM