这是一段针对C++17的短小程序:
我该如何在编译时区分能够转换为
这个问题与“为什么if constexpr使核心常量表达式错误消失不了?”不同,因为它不涉及模板(即使对于此情况,正确的用法可能是在模板上下文中)。即使主题相关,但这个问题本身也是不同的。
这个问题与“非模板类型的Constexpr if”不同,因为它具体涉及到
#include <iostream>
#include <string>
using namespace std::string_literals;
int main() {
std::string n = "asdf"s;
if constexpr (std::is_integral<decltype(n)>::value) {
std::cout << static_cast<int>(n) << std::endl;
} else {
std::cout << n << std::endl;
}
return 0;
}
但是它无法编译,因为显然 is_integral
认为 std::string
是整数型:
g++ -o main.o -c -std=c++17 -O2 -pipe -fPIC -fno-plt -fstack-protector-strong -Wall -Wshadow -pedantic -Wno-parentheses -Wfatal-errors main.cpp
main.cpp: In function 'int main()':
main.cpp:10:40: error: invalid static_cast from type 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to type 'int'
std::cout << static_cast<int>(n) << std::endl;
^
compilation terminated due to -Wfatal-errors.
我该如何在编译时区分能够转换为
int
的内容和不能转换的内容?这个问题与“为什么if constexpr使核心常量表达式错误消失不了?”不同,因为它不涉及模板(即使对于此情况,正确的用法可能是在模板上下文中)。即使主题相关,但这个问题本身也是不同的。
这个问题与“非模板类型的Constexpr if”不同,因为它具体涉及到
std::is_integral
的行为。
if constexpr
的正确使用仅限于模板中,如果条件取决于模板参数。 - HolyBlackCatstd::is_integral<std::string>::value
的值为false
。直接替换为false
即可,问题不会改变。 - rustyx