提问人:CPW 提问时间:10/27/2023 最后编辑:HolyBlackCatCPW 更新时间:10/28/2023 访问量:52
为什么 decltype 和 is_same 的组合会产生错误的结果?
Why the combination of decltype and is_same gives wrong result?
问:
我有以下功能:
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
}
在 VSCode 中运行上述断言测试:
- int 测试正确地进入 int 大小写。
- 双重测试在运行时错误地进入另一种情况。
- char* 大小写在编译时大小写中错误地进入双大小写。
我对双重情况进行了以下更改,所有更改的结果都相同:
- 双倍&
- 多布勒
- 常量双人间
- 常量双&
为什么会这样?
答:
0赞
CPW
10/28/2023
#1
正如 HolyBlackCat 所指出的,正确答案是:
template<typename T> auto print_type_info(const T& t) { // C++17
if constexpr (std::is_same<T, int>::value) {
return t + 1;
} else if constexpr (std::is_same<decltype(t), const double&>::value) {
return t + 0.1;
} else {
return t;
}
}
评论
const double &
==
strcmp
string_view
0.1 + 0.1
0.2