我想根據運行時值創建一個具有非型別引數的型別,make_fruit函式:
struct IFruit {
// interface
};
enum Species {
Apple,
Orange,
Peach,
};
enum Color {
Red,
Green,
Blue,
Yellow,
};
template <Species S, Color C> struct Fruit : public IFruit {
// impl
};
IFruit* make_fruit(Species s, Color c) {
// return new Fruit<s, c>
}
有干凈的方法嗎?如,不寫 12 個 switch 案例。
編輯:注意: classesIFruit和FruitenumsColor是Species(由某些庫)給出的,不能修改。
uj5u.com熱心網友回復:
簡短的回答:不!
長答案:仍然沒有,但您可以通過創建中間嵌套函式讓您的生活更輕松。每個函式都針對您已經處理過的列舉進行了模板化,并且有一個用于單個列舉的開關。因此,您無需撰寫 12 個條件,而是僅撰寫 7 個條件,并且存在的值越多,使用這種方法節省的就越多。
template <Species s>
IFruit* make_fruit_of_species(Color c) {
//your switch for color here
}
IFruit* make_fruit(Species s, Color c) {
// your switch for species here, returning a value with make_fruit_of_species
}
但我想知道你是否真的需要一個模板來處理這樣一個簡單的案例。也許你只需要一個型別種類的成員和一個型別顏色。
uj5u.com熱心網友回復:
std::visit由于以下原因,您可以避免自己撰寫組合std::variant:
using SpeciesVariant = std::variant<
std::integral_constant<Species, Species::Apple>,
std::integral_constant<Species, Species::Orange>,
std::integral_constant<Species, Species::Peach>
>;
using ColorVariant = std::variant<
std::integral_constant<Color, Color::Red>,
std::integral_constant<Color, Color::Green>,
std::integral_constant<Color, Color::Blue>,
std::integral_constant<Color, Color::Yellow>
>;
SpeciesVariant to_variant(Species s)
{
switch (s) {
case Species::Apple: return std::integral_constant<Species, Species::Apple>{};
case Species::Orange: return std::integral_constant<Species, Species::Orange>{};
case Species::Peach: return std::integral_constant<Species, Species::Peach>{};
}
throw std::runtime_error("Bad argument");
}
ColorVariant to_variant(Color c)
{
switch (c) {
case Color::Red: return std::integral_constant<Color, Color::Red>{};
case Color::Green: return std::integral_constant<Color, Color::Green>{};
case Color::Blue: return std::integral_constant<Color, Color::Blue>{};
case Color::Yellow: return std::integral_constant<Color, Color::Yellow>{};
}
throw std::runtime_error("Bad argument");
}
最后:
std::unique_ptr<IFruit> make_fruit(Species s, Color c)
{
return std::visit([](auto s, auto c) -> std::unique_ptr<IFruit> {
return std::make_unique<Fruit<s, c>>();
}, to_variant(s), to_variant(c));
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417716.html
標籤:
上一篇:從.txt檔案中讀取浮點數的問題
下一篇:如果比較qstrings時崩潰
