【发布时间】:2012-12-13 21:58:12
【问题描述】:
更新:我在下面发布了自己的答案 这里有一个更长的版本: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),然后我确保该值适合在一个签名长长的。
这一切都很好(太大的值会导致编译错误),但只有当我显式创建变量时,例如
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。
【问题讨论】: