c++11的constexpr关键字 literal(常量)

本文探讨了C++11中constexpr关键字的作用,它用于确保变量在编译时为常量表达式。介绍了常量表达式的概念,即其值不可变且能在编译时求值。通过示例,说明了即使初始值是字面量,如果变量类型不是const修饰的,也不能视为常量表达式。同时,自定义类和某些库类型如IO和字符串不属于字面量类型,因此不能声明为constexpr变量。这主要因为自定义类可能未初始化成员值,不具备字面量类型的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

a constant expression is an expression whose value can’t change and that can be evaluated at a compile time. a literal is a constant expression.
whether a given object or expression is a constant expression depends on the types and the initializers. For example:

const int max_files = 20; // max_files is a constant expresion
int staff_size = 27; //staff_size is not a constant expression
const int sz = get_size(); //sz is not a constant expression

对于staff_size,尽管初始化值(initializer)是一个literal,但是它本身是一个plain int, not a const int,所以staff_size不是一个constant exprssion.
而对于sz来说,它的initializer的值在编译的时候才能够确定,所以sz不是一个constant expression.
in a large system, it can be difficult to determine for certain that an initializer is a constant expression.
under the new standard, we can ask the compiler to verify that a variable is a constant expression by declaring the variable in a constexpr declaration.
c++primer上举的几个例子是这样

constexpr int mf = 20; // 常量表达式  
constexpr int limit = mf + 1; // 常量表达式  
constexpr int sz = size(); // 如果size()是常量表达式则编译通过,否则报错  

我自己试了一下:

int size()
{
        return -1;
}
int main()
{
        constexpr int sz = size();
        return 0;
} 
xiahuixia@xiahuixia-Inspiron-3437:~/c++/primercode$ g++ -o constexpr constexpr.cpp -std=c++0x

结果是:

constexpr.cpp: In functionint main()’:
constexpr.cpp:8:26: error: call to non-constexpr functionint size()constexpr int sz = size();
                          ^

再来看看这个literal这个英文的意思,有点晦涩
c++primer是这样解释的:
the types we can use in a constexpr are known as “literal types”
because they are simple enough to have literal values.
of the types we have used so far, the arithmetic, reference, and pointer types are literal types.
但是,问题来了,our self-defined class type and the library IO and string types are not literal types. hence, we can’t define variables of these types as constexprs.
也就是说我们自定义的类和IO库还有字符串不是literal type类型。
为什么呢?且拿我们自定义的类来说吧。
比如说

class a{
int i;
char c;
}
a my_a;
my_a.i = ....
my_a.c = ....

类a的成员值在声明的时候或许根本没有初始化。所以不能称得上是literal type.(暂时我还不确定我的假设是不是正确的)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值