简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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