简体   繁体   English

在可变参数模板中使用sizeof运算符可在递归结束时跳过该函数

[英]Use of sizeof operator in Variadic Template to skip the function for the end of recursion

I am trying to use operator sizeof... to skip the function for the end of recursion by not calling it if there are no argument 我正在尝试使用运算符sizeof...如果没有参数,则不通过调用来跳过递归函数

#include<iostream>

template<typename T, typename ...Types>
void Display(T firstArg, Types...Args)
{  
    std::cout << firstArg << "\n";
    std::cout << sizeof...(Types) << "\n";
    std::cout << sizeof...(Args) << "\n";
    if (sizeof...(Args) > 0)
    Display(Args...);
}

int main()
{
    Display(1, 2, 3,"hello");
    return 0;
}

But I am getting following error for Display(Args...); 但是我在Display(Args...);

error C2780: 'void Display(T,Types...)': expects 2 arguments - 0 provided 错误C2780:'无效显示(T,Types ...)':需要2个参数-提供0

Workaround is to add function for the end of recursion (which I want to avoid) 解决方法是在递归结束时添加功能(我想避免)

void Display()
{

}

Question is how to avoid end of recursion function 问题是如何避免递归函数结束

You can't do this without some workaround, pre-C++17, unless you rewrite the function to not be recursive. 在C ++ 17之前的版本中,如果没有一些解决方法就无法做到这一点,除非您重写该函数以使其不递归。 The reason is that the entire function body is substituted, including branches of if statements that can never happen. 原因是整个函数体被替换,包括if语句的分支,这些分支永远不会发生。 That means that the compiler sees the call to Display() with no arguments, even though it would never have happened at runtime. 这意味着即使在运行时从未发生过,编译器也可以看到不带参数的Display()调用。

Since C++17, the solution to this is to use if constexpr instead of just if . 从C ++ 17开始,解决此问题的方法是使用if constexpr而不是if That tells the compiler to evaluate the condition at compile time, and not try to compile the branch which doesn't execute. 这告诉编译器在编译时评估条件,而不尝试编译未执行的分支。

Note that “not try to compile” above is a simplification; 注意上面的“不尝试编译”只是一种简化; the link has more details about what exactly is and isn't done. 该链接提供了有关确切完成和未完成操作的更多详细信息。

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

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