Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I fail compilation based on constexpr if?

Is there a workaround to do something like this?

if constexpr (std::floating_point<T>) {}
else if constexpr (std::integral<T>) {}
...
else static_failure("Feature expansion needed");

because if I replace static_failure with static_assert, it needs the replication of all the above conditions (they are many and complicated) and it becomes ugly.

// It does not work properly: always fail
else static_assert(false, "Feature expansion needed");
// works fine, but it is ugly
else static_assert(std::floating_point<T> || std::integral<T> || ... || ... || ..., "Feature expansion needed");

I do not prefer a runtime behavior like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

throw "Feature expansion needed";

>Solution :

Yes, you just need the static assert to be dependant on T and always be false like this:

if constexpr (std::is_integral_v<T>) {}
else
    static_assert(sizeof(T) < 0, "Only works for integral T");

https://godbolt.org/z/Yhesd58rK

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading