gpt4 book ai didi

c++ - 编译时类型转换检查(constexpr 和用户定义的文字)

转载 作者:可可西里 更新时间:2023-11-01 18:29:35 26 4
gpt4 key购买 nike

更新:我在下面发布了我自己的答案这里有一个更长的版本:http://scrupulousabstractions.tumblr.com/post/38460349771/c-11-type-safe-use-of-integer-user-defined-literals

问题:

我制作了一个简单的 constexpr 用户定义文字 _X 获取值作为 unsigned long long(这就是数字用户定义文字的工作方式:http://en.cppreference.com/w/cpp/language/user_literal) ,然后我确保该值适合 signed long long。

一切正常(太大的值会导致编译错误),但只有当我显式创建一个变量时,例如

constexpr auto a= 150_X;

如果我写一些典型的东西,比如

cout << 150_X << endl;;

测试不会在编译时执行。

  • 如果将 constexpr 函数分配给 constexpr 变量,它们是否仅在编译时执行? (我在标准中找不到)

  • 是否有可能实现我正在寻找的 _X 的安全行为?

完整示例:

#include<iostream>
#include<stdexcept>

inline constexpr long long testConv(unsigned long long v) {
return (v > 100 ) ? throw std::exception() : v;
} // will eventually use actual limit from numeric_limits

inline constexpr long long operator "" _X(unsigned long long f) {
return testConv(f) ;
}

int main(){
constexpr auto a= 5_X;
std::cout << a << std::endl;
std::cout << 200_X << std::endl; // This bad literal is accepted at compile time
constexpr auto c=250_X; // This bad literal is not accepted at compile time
std::cout << c << std::endl;
}

哦,供引用:我用的是gcc4.7.2。

最佳答案

self 回答:我找到了一个完整的解决方案,灵感来 self 的问题的评论和其他答案,以及其他问题,例如 https://stackoverflow.com/a/13384317/1149664 .

解决方案是使用用户自定义字面量的模板形式,手动求和,根据已解析的数字求和乘以10。

我在这里写了这个 self 回答的详细版本:http://scrupulousabstractions.tumblr.com/post/38460349771/c-11-type-safe-use-of-integer-user-defined-literals

template<char... Chars>
int operator"" _steps(){
return {litparser<0,Chars...>::value};
}

Litparser 是一个小型模板元程序,它将字符列表作为从 Chars 参数包包含的输入字符扩展而来的参数。

typedef unsigned long long ULL;

// Delcare the litparser
template<ULL Sum, char... Chars> struct litparser;

// Specialize on the case where there's at least one character left:
template<ULL Sum, char Head, char... Rest>
struct litparser<Sum, Head, Rest...> {
// parse a digit. recurse with new sum and ramaining digits
static const ULL value = litparser<
(Head <'0' || Head >'9') ? throw std::exception() :
Sum*10 + Head-'0' , Rest...>::value;
};

// When 'Rest' finally is empty, we reach this terminating case
template<ULL Sum> struct litparser<Sum> {
static const ULL value = Sum;
};

关于c++ - 编译时类型转换检查(constexpr 和用户定义的文字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13869193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com