为什么 while 循环内的 Variadic 模板函数不打印到控制台?

Why doesn't the Variadic Template Function inside a while loop print to the console?

我想尝试使用可变参数模板函数打印语句并接受用户输入的标志控制的 while 循环语句?这可能吗?

#include <iostream>

template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }

template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }

auto main() -> int {

    int a;

    while(a > 100) {
        write("Enter a number: ");
        read(a);
    }
}
int a;

您声明了 a,但没有对其进行初始化,这意味着 a 未初始化并且可以保存一些随机值。

您可以通过使用大于 100 的值初始化 a 来解决此问题,例如:

int a = 101;

因此您的代码应如下所示:

#include <iostream>

template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }

template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }

auto main() -> int {

    int a = 101;

    while(a > 100) {
        write("Enter a number: ");
        read(a);
    }
}

如评论中所述,变量a未初始化。因此,该变量包含垃圾值,因此会导致 运行 时间错误。

因此首先初始化变量,然后运行一个while循环就可以了。 并且代码需要使用 variadic 模板函数来获取用户输入。所以你可以这样做:

#include <iostream>

template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }

template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }

auto main() -> int {

    int a;

    // To initialize a
    write("Enter a number: ");
    read(a);
    while(a > 100) {
        write("Enter a number: ");
        read(a);
    }
}

如果允许 do-while 循环,则以下也是可能的解决方案:

#include <iostream>

template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }
template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }

auto main() -> int {

    int a;

    do {
        write("Enter a number: ");
        read(a);
    }while(a > 100);
}