mercredi 5 décembre 2018

How to set variable value at compile time from an expression?

I am trying to assign sizeof values of some data type to variables at compile time.

I tried following code :

constexpr int foo_implementation () {
        return sizeof(int);
}
#define foo std::integral_constant<int, foo_implementation()>::value
int main() {
    int size;
    for(int i=0;i<10;i++) {
        size = foo;
        std::cout<<size<<std::endl;
    }
    return 0;
}

When i dump the output of preprocessor, it just replace foo with complete statement, which is expected.

My question is will compiler hardcode size to 4 (assuming size of int is 4) or will it call sizeof operator again and again.

If not, how can i fix the value of size at compile time at size of int is know at compile time, to save extra instructions execution at runtime?

Aucun commentaire:

Enregistrer un commentaire