【问题标题】:How can I check that function really get a variable that defined as const?如何检查该函数是否真的获得了定义为 const 的变量?
【发布时间】:2018-06-29 09:09:24
【问题描述】:

给定以下代码:

template <class Func>
void f(Func func , int* param){
   func(/* how can I send "param" as const "int*" */);
}

如果f 没有将变量设为 const,我该怎么做 - 所以我们会得到错误?

【问题讨论】:

  • 一些最少的代码可以方便地填空答案。
  • @chris 我编辑了我的问题(并添加了示例以澄清我的问题)。
  • 你想要哪一个? “常量指针”还是“指向常量的指针”?

标签: c++ c++11 constants


【解决方案1】:

如果您想确保 f 接受指向 const 限定的 int 的指针,您可以适当地转换函数参数:

f(static_cast<int const *>(param));

或者,如果您想确保 f 接受对 const 限定指针的引用,您可以将 const 限定符添加到函数参数:

void f(Func f , int * const param)

【讨论】:

  • 我也想过,但不是反其道而行之?也就是说,static_cast 不删除参数中的“const”?
  • @Software_t 删除const的是const_cast
  • 对不起,你说得对。你能解释一下在这种情况下我是否可以用dynamic_cast 来做(以及为什么)?
  • @Software_t:当然,那会退化为static_cast。恕我直言,他们应该在添加所有显式转换时添加no_cast,这里就足够了。
猜你喜欢
  • 2010-09-22
  • 2017-01-09
  • 1970-01-01
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
  • 2012-10-07
  • 1970-01-01
相关资源
最近更新 更多