我正在學習C++。 我想讓編譯器將nullptr推斷爲shared_ptr。 請仔細閱讀下面的代碼,如何讓編譯器推導出一種nullptr類型?
struct A {};
struct B {
std::shared_ptr<A> a;
};
struct Tag {
std::shared_ptr<B> b;
};
auto GetSharedPtrClassB(Tag* tag) {
if (tag) {
auto& sharedB = *(tag->b);
return sharedB.a;
} else {
return nullptr; // Error : compiler cannot deduce type of nullptr.
}
}
在GetSharedPtrClassB
,nullptr
不能推導出std::shared_ptr<A>
。 錯誤消息之後,
error: inconsistent deduction for ‘auto’: ‘std::shared_ptr<A>’ and then ‘std::nullptr_t’
我怎樣才能讓編譯器演繹nullptr爲std::shared_ptr<A>
? 我可以提供一個decltype(*(tag->b))
的類型,但我想不到下一步提供的類型std::shared_ptr<A>
。
非常感謝。
如何關於明確使用'std :: shared_ptr '作爲返回類型?或者在'else'情況下返回一個默認構造的'std :: shared_ptr '對象? –
@Someprogrammerdude:謝謝你的評論。在我的實際代碼中,類A可以是C,因爲元編程。所以我想讓推導出shared_ptr類型的<'X'>。 – mora
這是更好地展示實際的問題,因爲現在每個人都需要猜測哪種方法最適合([XY問題(https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)) ...另請參閱如何提出一個很好的問題:MCVE(https://stackoverflow.com/help/mcve) –