使用decltype(auto)返回指针或nullptr时的类型推导不一致问题
使用decltype(auto)返回指针时的类型推导问题及C++17/20解决方案
当把decltype(auto)用作预期返回指针的模板函数返回类型时,如果函数可能返回有效地址或nullptr,会出现类型推导不一致的问题。示例代码如下:
struct S { bool condition; int data; template <typename Self> static decltype(auto) GetByAddress(Self* self) { if (self->condition) { return &self->data; } return nullptr; } int* GetByAddress() { return GetByAddress(this); } int const* GetByAddress() const { return GetByAddress(this); } };
注:C23中可以使用推导this解决这个示例,但这里需要C17或C++20下的修复方案。
我可以使用std::optional或类似返回类型包装器,但更想了解如何对可能返回nullptr的指针进行自动类型推导。
在简化示例中,有如下解决方案:
static decltype(auto) GetByAddress(Self* self) { using ptr = decltype(&self->data); if (self->condition) { return &self->data; } return ptr{nullptr}; }
但该方案在更复杂场景中难以轻松应用。
内容的提问来源于stack exchange,提问作者Oersted
相关产品推荐
相关产品推荐

