mardi 29 septembre 2015

Checking if a variable is constant qualified

I was reading about const_cast and it seemed unsafe and not very helpful. The best answer about it in SO states the it would be useful in a scenario like this:

void func(const char* param, bool modify){
    if(modify)
        //const_cast and change param
    // stuff that do not change param
}

Although this a possible use, it has its risks because you have to correctly provide the value of "modify", or else you will get an undefined behaviour since you are changing something that was supposed to be constant. I wonder if you could achieve the same functionality without having to supply this extra argument and for that you would most likely need to check the existence of a const qualifier.

The closes thing I found was the std function is_const, but it seems to be limited to a different kind of usage:

is_const<const int>::value //returns true
is_const<int>::value // returns false
const int myVar=1;
is_const<myVar>::value // what it would look like ( does not compile)

I've also tried using similar function signatures that only differ by a "const" qualifier, but that is perceived as a redefinition. So is it possible at all to do it? If so, how can it be done?

Aucun commentaire:

Enregistrer un commentaire