gpt4 book ai didi

c++ - 如何实现将用户输入读取到提供的所有变量中的可变参数模板?

转载 作者:太空宇宙 更新时间:2023-11-04 15:00:38 25 4
gpt4 key购买 nike

我目前正在尝试自学可变参数模板。但是,我无法通过简单的添加模板来理解任何内容。

目前我想要一个可以执行以下操作的模板:

  1. 取任意数量的类型
  2. 获取需要用户以下列格式输入的参数:

    T值,字符串描述符

  3. 然后逐个遍历每个变量,在读取变量之前打印描述符

例如输出应该是这样的:

x (int) //this is the descriptor
//here something is being read into the variable x
y (int) //this is another descriptor
//something else is being read into y
.
.
.

因为它总是相同的操作,所以这应该是可能的。然而我最好的尝试是这样的

template<typename t,typename... Args>
void generic_reader(t first,string desc,Args... args)
{
cout<<desc<<endl;
cin>>first;
generic_reader(args);
}

显然这行不通。但是我想不出另一种方法。同样,我才刚刚开始使用可变参数模板。

谁能给我一个详细解释的解决方案?

最佳答案

这是一种使用递归的方法。

#include <iostream>

// provide a terminating case
void generic_read()
{
}

// provide the general case which picks off the first 2 arguments
// and forwards the rest to another version of itself.

template<typename T, typename Printable, typename...Rest>
void generic_read(T& value ,Printable&& desc,Rest&&...rest)
{
std::cout << desc << std::endl;
std::cin >> value;
generic_read(std::forward<Rest>(rest)...);
}

// test
int main()
{
int x;
double y;

generic_read(x, "an integer:", y, "a double");
}

关于c++ - 如何实现将用户输入读取到提供的所有变量中的可变参数模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46702778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com