简体   繁体   English

根据C ++中的用户输入更改模板类型

[英]Changing template type depending on user input in C++

My assignment was to create a Stack class template so that it can be used for other data types such as int, double, string, etc. What I'm stuck on is having a declaration of type-less Stack object right before the instantiation of it with the right type. 我的任务是创建一个Stack类模板,以便可以将其用于其他数据类型,例如int,double,string等。我坚持要做的是在实例化之前,声明一个无类型的Stack对象。它具有正确的类型。 Maybe it's because I'm searching wrong but I just can't find anything on having a base class that I can convert from. 也许是因为我搜索错误,但是在拥有可以转换的基类上却找不到任何东西。

//in the main method
//get user input, which will be "int", "string", "double", etc.
string type;
cin >> type;

MyStack<???> stack1;
if(type == "int")
//convert stack1 to MyStack<int>
else //same thing for other data types

You cannot. 你不能。 But you can solve the underlying problem. 但是您可以解决潜在的问题。 Here it is in using continuation passing style: 这是使用连续传递样式的中的

//in the main method
//get user input, which will be "int", "string", "double", etc.
std::string type;
std::cin >> type;

[&](auto&&next){
  if(type == "int")
    return next(MyStack<int>{});
  else if (type=="string")
    return next(MyStack<std::string>{});
  else if (type=="double")
    return next(MyStack<double>{});
  else
    throw std::invalid_argument(type);
}([&](auto&& stack1){
  // Here stack1 is the correct type
});

this probably is not what your instructor was asking you to do. 这可能不是您的老师要您做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM