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

const_cast与std::remove_reference配合失效问题及修复咨询

问题描述

我尝试实现功能的最简示例代码如下:

#include <array>

int main() {
    std::array<int, 5>* arr = new std::array<int, 5>{}; // no fill
    int** temp = new int*;

    for (const auto& e : *arr) {
        // some code that uses e...
        *temp = const_cast< std::remove_reference<decltype(e)>* >(&e); //error
        *temp = const_cast< int* >(&e); //ok
    }

    **temp = 22;
}

我想通过decltype获取e的类型,移除引用后转为指针来指向e,但代码报错:

invalid 'const_cast' from type 'const int*' to type 'std::remove_reference<const int&>*'

请问该如何修复?


修复方案

问题出在std::remove_reference的使用语法和类型处理上:你直接写std::remove_reference<decltype(e)>*会被解析成指向std::remove_reference模板实例的指针,这完全不是你需要的基础类型指针。同时你还需要明确处理const限定符的转换逻辑。

正确写法(C++14及以上)

使用std::remove_reference_t直接获取移除引用后的基础类型,再添加指针声明:

*temp = const_cast< std::remove_reference_t<decltype(e)>* >(&e);

C++11兼容写法

如果需要兼容C++11,要加上typename来指明嵌套类型:

*temp = const_cast< typename std::remove_reference<decltype(e)>::type* >(&e);

逻辑解释

  1. decltype(e)得到的类型是const int&
  2. std::remove_reference_t<decltype(e)>会移除引用,得到const int
  3. 后缀*将其转为const int*,再通过const_cast去掉const限定,最终得到匹配temp类型的int*

注意:这里修改原对象的行为合法,是因为原数组元素本身是int(非const);如果原对象本身是const属性,通过const_cast修改会触发未定义行为,需谨慎使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:27:35