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

标签 c++ c++11 templates variadic-templates

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

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

  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/

相关文章:

c++ - 如何正确地将回调函数从 swift 传递到 C++?

c++ - GCC 拒绝使用 enum-base 的简单声明; clang 接受它——这是正确的吗?

c++ - 覆盖 operator new 以合并 PIMPL 分配

PHP 最佳设计实践

c++ - 奇怪的输出 : why would this code give any meaningful output, 更不用说这个了?

c++ - Jenkins 上的 Coverity 有什么替代品吗?

c++ - 使用时如何重置 std::cin?

c++ - 如何将从文件读取的字符串关联到枚举值?

c++ - 在基于范围的循环中使用 lambda 的初始化列表

c++ - try catch 模板类中定义的异常