如何通过c++中的参考来传递模板variadic参数?

发布于 2025-01-24 20:31:02 字数 1180 浏览 2 评论 0原文

我想获得重复的输入,因此我制作了该功能,以获取具有多种类型的输入。

template <typename InputType>
void get_inputs(const std::string& placeholder, InputType& input){
    std::cout << placeholder << ": ";
    std::cin >> input;
}

template <typename InputType, typename... Args>
void get_inputs(const std::string& placeholder, InputType& input, Args... args){
    get_inputs(placeholder, input);
    get_inputs(args...);
}

int main(int, char**) {
    std::string name;
    int age;
    double height;

    get_inputs(
        "name", name,
        "age", age,
        "height", height
    );

    std::cout << "INFO: " << name << ", " << age << ", " << height << std::endl;

    return 0;
}

如果我输入(正方形括号中的内容是用户输入)

输入

名称:[示例名称]
年龄:20
身高:173.5

然后结果必须为

输出

信息:示例名称,20,173.5

但是,结果是

输出

信息:示例名称,1,2.12785e-314

我注意到只有第一个参数是通过引用传递的,并且遗骸是按值传递的。我认为由于get_inputs功能而引起的问题。我该如何解决?

I want to get repeated inputs, therefore I made the function to get inputs with variety of types.

template <typename InputType>
void get_inputs(const std::string& placeholder, InputType& input){
    std::cout << placeholder << ": ";
    std::cin >> input;
}

template <typename InputType, typename... Args>
void get_inputs(const std::string& placeholder, InputType& input, Args... args){
    get_inputs(placeholder, input);
    get_inputs(args...);
}

int main(int, char**) {
    std::string name;
    int age;
    double height;

    get_inputs(
        "name", name,
        "age", age,
        "height", height
    );

    std::cout << "INFO: " << name << ", " << age << ", " << height << std::endl;

    return 0;
}

And if I enter like (the content enclosed in square bracket is user input)

Input

name: [example-name]
age: 20
height: 173.5

then the result must be

Output

INFO: example-name, 20, 173.5

However, the result is

Output

INFO: example-name, 1, 2.12785e-314

I noticed that only the first argument was passed by reference, and the remains were passed by value. I think the problem caused by not well-defined get_inputs functions. How can I solve it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文