0

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

Wang
  • 13
  • 3

1 Answers1

0

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;
    }
}
Mikdore
  • 699
  • 5
  • 16