Here's a short program for C++17:
#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;
}
But it does not compile, since apparently, is_integral
thinks that the std::string
is integral:
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.
How can I differentiate at compile-time between something that can be cast to int
, and something that can not?
This question is not the same as "Why doesn't an if constexpr make this core constant expression error dissappear?", since it's not about templates (even though the correct usage, for this case, may be within the context of a template). The question itself is also different, even if the topic is related.
This question is not the same as "Constexpr if with non-template types", because it's specifically about the behavior of std::is_integral
.