You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 18:22:05