4 ms·
Is there no way to indicate to GCC when you want something fully evaluated at compile-time? Maybe some pragmas? 98% of the time I probably don't care whether GC
by harpocrates 10y ago
Is there no way to indicate to GCC when you want something fully evaluated at compile-time? Maybe some pragmas? 98% of the time I probably don't care whether GCC does a good job optimizing this properly, but for the times I do care: what should I do?
- lultimouomo 10y agoc++ has constexpr for this. a constexpr expression will be evaluated at compile time if the result is used in a constant expression (i.e. assignd to an enum constant or a constexpr variable), or an error will be generated if it is not possible to do so (the expression does not fulfill the requirements to be constexpr).
- matt_d 10y agoA `constexpr` function storing result in a `constexpr` variable (you need both for the compile-time evaluation guarantee): http://en.cppreference.com/w/cpp/language/constexpr http://en.cppreference.com/w/cpp/language/constexpr An extra complication in this example is that `std::accumulate` currently lacks `constexpr` support: http://stackoverflow.com/questions/32395408/why-arent-stdalgorithms-constexpr-and-which-could-be http://stackoverflow.com/questions/32395408/why-arent-stdalg... There's been a proposal to relax this limitation: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0202r0.html http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p020... For now you could use a workaround in form of a range-based for loop: https://godbolt.org/g/aVEqlm https://godbolt.org/g/aVEqlm or even https://godbolt.org/g/GDrFr5 https://godbolt.org/g/GDrFr5 (homogeneous types). A fold expression is much cleaner, though (also supporting heterogeneous types): https://godbolt.org/g/Hrnkc1 https://godbolt.org/g/Hrnkc1
- andrepd 10y agoUse constexpr: http://en.cppreference.com/w/cpp/language/constexpr http://en.cppreference.com/w/cpp/language/constexpr You can't make sum constexpr in this case, though, since it calls a non-constexpr function, accumulate.