Is there some ninja trick to make a variable constant after its declaration?

后端 未结 8 1401
广开言路
广开言路 2020-12-01 09:13

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 ex         


        
8条回答
  •  一生所求
    2020-12-01 09:35

    Why not refactor your code in to two separate functions. One that returns a modified a and another that works on this value (without ever changing it).

    You could possibly wrap your object too around a holder class object and work with this holder.

    template 
    struct Constify {
        Constify(T val) : v_( val ) {}
        const T& get() const  { return v_; }
    };
    
    void SomeFuncion() {
        Constify ci( Compute() ); // Compute returns `a`
        // process with ci
    }
    

    Your example has an easy fix: Refactoring.

    // expect a lowercase path or use a case insensitive comparator for basic_string
    void OpenFile(string const& path)  
    {        
        // I want path to be constant now
        ifstream ...
    }
    
    OpenFile( boost::to_lower(path) ); // temporaries can bind to const&
    

提交回复
热议问题