I have the following function:
template<typename T> auto print_type_info(const T& t) { // C++17
if constexpr (std::is_same<T, int>::value) {
return t + 1; // int case
} else if constexpr (std::is_same<decltype(t), double&>::value) {
return t + 0.1; // double case
} else {
return t; // other case
}
}
void main() {
assert(print_type_info(1) == 2); // int test
assert(print_type_info(0.1) == 0.2); // double test
assert(print_type_info("0") == "0"); // char* test
}
Runing the above assert tests in VSCode:
- int test goes into the int case correctly.
- double test goes into the other case wrongly in run-time.
- char* case goes into the double case wrongly in compile-time case.
I have made the following changes for the double case all with the same result:
- double&
- dobule
- const double
- const double&
Why is this?
As pointed out by HolyBlackCat, the correct answer is: