Search code examples
c++scopeauto

scope of const auto variables


I have a simple function

void simpleFunction(){

const auto img= getImageSomehow();

// do something with img
}

it works ok. However I want to modify this function to include a boolean there as:

void simpleFunction(bool isGPU){

if(isGPU){
        const auto img= getImagefromGPU();
}
else{
    const auto img= getImageSomehow();
}
// do something with img
}

However this is not correct right? since the scope of the auto variable img does not reach the operations in "do something with img"

This does not work either

void simpleFunction(bool isGPU){
 const auto img;    
if(isGPU){
        img= getImagefromGPU();
}
else{
    img= getImageSomehow();
}
// do something with img
}

since the declaration has no initializer.

Is there a way to somehow do this? in other words, get the img depending on the bool and then work with it?


Solution

  • One option is to refactor the code that "does something with img" into a template

    template<typename ImageType>
    void do_something(ImageType const img)  // img is const here as desired
    {
      // do something with img
    }
    

    and then your original function becomes

    void simpleFunction(bool isGPU)
    {
      if(isGPU) 
        do_something(getImagefromGPU());
      else
        do_something(getImageSomehow());
    }