在下面的示例中,我希望在编译时被告知,从 long 到 int 的转换会更改值,就像我不使用用户定义的文字时所做的那样。
#include <cassert>
constexpr int operator "" _asInt(unsigned long long i) {
// How do I ensure that i fits in an int here?
// assert(i < std::numeric_limits<int>::max()); // i is not constexpr
return static_cast<int>(i);
}
int main() {
int a = 1_asInt;
int b = 99999999999999999_asInt; // I'd like a warning or error here
int c = 99999999999999999; // The compiler will warn me here that this isn't safe
}
Run Code Online (Sandbox Code Playgroud)
我可以找出几种获得运行时错误的方法,但我希望有某种方法可以使其成为编译时错误,因为据我所知,所有元素都可以在编译时已知。
Art*_*yer 24
做了consteval:
consteval int operator "" _asInt(unsigned long long i) {
if (i > (unsigned long long) std::numeric_limits<int>::max()) {
throw "nnn_asInt: too large";
}
return i;
}
int main() {
int a = 1_asInt;
// int b = 99999999999999999_asInt; // Doesn't compile
int c = 99999999999999999; // Warning
}
Run Code Online (Sandbox Code Playgroud)
在 C++17 中,您可以使用文字运算符模板,但它有点复杂:
template<char... C>
inline constexpr char str[sizeof...(C)] = { C... };
// You need to implement this
constexpr unsigned long long parse_ull(const char* s);
template<char... S>
constexpr int operator "" _asInt() {
constexpr unsigned long long i = parse_ull(str<S..., 0>);
static_assert(i <= std::numeric_limits<int>::max(), "nnn_asInt: too large");
return int{i};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
835 次 |
| 最近记录: |