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

Infer type information inside if-constexpr

I want to explore the feature of if-constexpr and try to figure out type information at compile-time.
For this purpose, I write the following code.
I expect that printTypeInfo function will return 4 for x and 3.24 for y. However, it gives me 3.1 and 3.24.
I don’t know where goes wrong.
enter image description here

I wish decltype will infer the type to int, but it seems infer to double.
When I replace decltype with following code, it works.
enter image description here

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

>Solution :

decltype(value) in your example will always be const T&, since that’s your parameter type. References aren’t integral, so you always add 0.1. You could use std::remove_reference_t to get the underlying type:

auto printTypeInfo(const auto& value) {
    if constexpr (std::is_integral_v<std::remove_reference_t<decltype(value)>>) {
        return v + 1;
    } else {
        return v + 0.1;
    }
}
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