【问题标题】:Changing template type depending on user input in C++根据 C++ 中的用户输入更改模板类型
【发布时间】:2018-07-01 22:34:52
【问题描述】:

我的任务是创建一个 Stack 类模板,以便它可以用于其他数据类型,例如 int、double、string 等。我坚持的是在之前声明无类型 Stack 对象用正确的类型实例化它。也许是因为我搜索错误,但我找不到任何可以转换的基类。

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

【问题讨论】:

  • 模板类型参数是静态解析的。您不能让它是开放式的并依赖于运行时值。如果您的类型集有限,您可以分支到使用正确类型的不同函数。
  • @StoryTeller 那么我可以通过将默认模板类型设置为 int 在运行时将其转换为不同的模板类型吗?
  • 不,演员表的类型也是静态确定的。 C++ 是一种静态类型语言。当你假装它拥有std::string 时,为什么你认为一堆int 会正确运行?
  • 我不清楚您的分配如何暗示您需要使上述代码正常工作。
  • @StoryTeller 哈哈,我只是希望出于绝望和懒惰。然后我猜我应该使用你建议的方法。但我不是很明白,你能详细说明一下吗?

标签: c++ class templates casting stack


【解决方案1】:

你不能。但是你可以解决根本问题。这里是,使用延续传递风格:

//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
});

这可能不是你的导师要求你做的。

【讨论】:

  • 我很想看看老师们的表情,但是:)
  • 我实际上会研究您的解决方案并尝试理解它。我非常决心用这个通宵完成我的项目(或至少一半)。如果我理解并使其正常工作,请提前感谢,否则仍然感谢:)
  • @unum 不,这是错误的响应。你想要某样东西,而我却如愿以偿。不像魔鬼,我会警告你你不想要你想要的。你误解了任务的要求,要求你误解的东西,如果你继续走这条路,你就注定要失败。我的爱好是用 C++ 做不可能的事情:你的导师并没有要求你做上述事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
  • 2017-09-23
  • 2013-04-11
相关资源
最近更新 更多