如何通过c++中的参考来传递模板variadic参数?
我想获得重复的输入,因此我制作了该功能,以获取具有多种类型的输入。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论