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

为何作为非类型模板参数的引用必须添加const限定符?

C++模板引用参数为何要区分const限定符?

我熟悉const在运行时代码中的行为逻辑,这完全合理,但鉴于“编译期操作均为常量”(并非标准表述),我疑惑C++为何要区分引用是否带有const限定符。

尤其如下示例在移除const后无法编译:

struct Country {
    std::string_view name;
};

template<const /* <-- required */ Country& country>
struct S{
    void print() {
        fmt::print("{}\n", country.name);
    }
};

static constexpr Country sg{.name="Singapore"};
int main() {
    
    S<sg> sg_printer;  
    sg_printer.print();    
}

GCC报错信息大致为:

error: binding reference of type 'Country&' to 'const Country' discards qualifiers

我猜测要么是未考虑该场景,要么是为了与常规代码保持一致性才如此设计。


内容的提问来源于stack exchange,提问作者NoSenseEtAl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:22:34