[英]Is there a way of changing the type used in a struct depending on at template parameter in c++?
[英]Changing template type depending on user input in C++
我的任務是創建一個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
你不能。 但是您可以解決潛在的問題。 這是使用連續傳遞樣式的c ++ 14中的代碼 :
//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
});
這可能不是您的老師要您做的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.