有没有一些忍者的技巧,使其变量常量后声明? [英] Is there some ninja trick to make a variable constant after its declaration?

查看:142
本文介绍了有没有一些忍者的技巧,使其变量常量后声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道答案是99.99%没有,但我认为这是值得一试,你永远不知道。

  SomeFunction(int a)
{
//这里有一些处理,例如:
a * = 50;
a%= 10;
if(example())
a = 0;
//从这一点上我想使aconst;我不想允许
//任何超过这个注释的代码以任何方式修改它。
}



我可以做一些类似于 const int b = a; ,但它不是真的相同,它造成了很多困惑。

编辑:另一个抽象不太好的例子,一个让我问这个问题:

/ p>

  void OpenFile(string path)
{
boost :: to_lower(path);
//我想让路径成为常数
ifstream ...
}

EDIT :另一个具体示例:在并行部分中的变量上重新捕获常量

解决方案

一个解决方案是将所有的突变代码放入lambda表达式。执行lambda表达式中的所有变异,并将结果分配给方法范围中的 const int 。例如

  void SomeFunction(const int p1){
auto calcA = [& $ b int a = p1;
a * = 50;
a%= 10;
if(example())
a = 0;
..
return a;
};
const int a = calcA();
...
}


I know the answer is 99.99% no, but I figured it was worth a try, you never know.

void SomeFunction(int a)
{
    // Here some processing happens on a, for example:
    a *= 50;
    a %= 10;
    if(example())
       a = 0;
    // From this point on I want to make "a" const; I don't want to allow
    // any code past this comment to modify it in any way.
}

I can do something somewhat similar with const int b = a;, but it's not really the same and it creates a lot of confusion. A C++0x-only solution is acceptable.

EDIT: another less abstracted example, the one that made me ask this question:

void OpenFile(string path)
{
    boost::to_lower(path);
    // I want path to be constant now
    ifstream ...
}

EDIT: another concrete example: Recapture const-ness on variables in a parallel section.

解决方案

One solution would be to factor all of the mutation code into a lambda expression. Do all of the mutation in the lambda expression and assign the result out to a const int in the method scope. For example

void SomeFunction(const int p1) { 
  auto calcA = [&]() {
    int a = p1;
    a *= 50;
    a %= 10;
    if(example())
       a = 0;
    ..
    return a;
  };
  const int a = calcA();
  ...
}

这篇关于有没有一些忍者的技巧,使其变量常量后声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆