![](/img/trans.png)
[英]what should I return if I don't have something to return for an unknown type
[英]What should I do if I have to declare a variable when I don't know the type for it?
我有這樣的代碼
if (...) {
const auto & h = std::make_shared<ClassB>();
... // here may be the function that uniquely belongs to ClassB
...
}
else (...) {
const auto & h = std::make_shared<ClassC>();
... // here may be the function that uniquely belongs to ClassC
...
}
h->someFunction();
上述代碼的最后一行無效,因為我使用了在 if-else 子句中聲明的變量。 要使用h
我必須在 if-else 子句之前聲明它。 但是我不能,因為在進入之前我不知道h
屬於什么類型。
我知道我可以使用三元運算符聲明它。
但我不想這樣做,因為我認為同時擁有三元運算符和 if-else 子句是多余的。
對不起,我不能。 編譯器會報錯“錯誤:條件表達式不明確;”。
有沒有辦法只保留一個 if-else 子句(沒有三元運算符),我仍然可以在 if-else 子句之外引用 h ?
我不能[使用三元運算符]。 編譯器會報錯“錯誤:條件表達式不明確;”。
您可以,您只需通過將兩個表達式之一轉換為基本 class 指針來消除結果類型的歧義:
auto const h = …
? init_class_b()
: static_cast<std:unique_ptr<BaseClass>>(init_class_c());
在這里, init_class_*
是包含兩個if
分支的主體的函數/lambdas。 也就是說,他們創建了 object 並在其上運行獨特的功能。 但是作為代碼設計的一點,如果需要這種獨特的操作,他們不應該將 go 放入 class 構造函數中嗎?
(與您的代碼不同,我沒有引用h
。 const 引用的終身擴展很棘手,在這里沒有必要。)
很難說最好的方法是什么。 您可以在 if 語句之外聲明h
:
auto h = std::shared_ptr<SuperClass>{}; // is now nullptr
if (...) {
h = std::make_shared<ClassB>
... // here may be the function that uniquely belongs to ClassB
...
}
else (...) {
h = std::make_shared<ClassC>
... // here may be the function that uniquely belongs to ClassC
...
}
h->someFunction();
如果 ClassB 和 ClassC 沒有實現someFunction
的公共超級 class ,這是不可能的*。 編譯器需要一些類型信息才能生成代碼。
*) 好的,有std::variant
和std::any
,但是在這個級別上,如果你開始走這條路,你不會幫自己一個忙。 還有其他方法(例如,static 多態性又名模板),但同樣,這些是為更特殊的情況保留的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.