简体   繁体   中英

C++ Variable Template. This is UB?

I created a simple C++14 variable template that calculates factorials (just for learning). Then I want print the first 12 factorials.

template <int n> const int fact = n * fact<n - 1>;
template <> const int fact<0> = 1;

If I replace fact<12> with fact<i> in following snippet, I get an error, because i is not constant.

int main()
{   
    for(int i = 0; i < 12; i++){
        std::cout << fact<12> << std::endl;
    }
}

But when I change it to this, I get the expected result.

int main()
{   
    for(int i = 0; i < 12; i++){
        std::cout << *(&fact<12> - i) << std::endl;
    }
}

Is this Undefined Behavior? It's working as expected on GCC 8.3. Live example here

It is UB. Your pointer arithmetic "works by chance" (with UB anything can happen).

You might do, instead, for example:

template <std::size_t ... Is>
void print_fact(std::index_sequence<Is...>)
{
    for (int res : {fact<Is>...}) {
        std::cout << res << std::endl;
    }
}

int main()
{
    print_fact(std::make_index_sequence<12>());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM