C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ constexpr 与 explicit使用

C++中constexpr 与 explicit关键字使用实战样例

作者:点云SLAM

文章详细介绍了constexpr和explicit关键字在C++中的用途和用法,constexpr用于声明实体可以在编译期求值,而explicit用于阻止不期望的隐式类型转换,本文结合实例代码介绍的非常详细,感兴趣的朋友跟随小编一起看看吧

概述

一、constexpr深度讲解

1. 含义(核心语义)

constexpr 表示:函数/构造器/变量在满足条件时可以在编译期求值,从而能用作常量表达式(用于数组维度、模板非类型参数、static_assert 等)。

2. 演进变化

constexpr 的能力随标准放宽:

新关键词对比(C++20)

3.constexpr的常见用法示例

3.1constexpr变量

constexpr int square(int x) { return x * x; }   // C++14 起允许复杂体
constexpr int five = 5;
constexpr int twentyfive = square(five);         // 编译期求值
static_assert(twentyfive == 25);

3.2constexpr函数(运行期与编译期两用)

constexpr int fib(int n) {
    if (n <= 1) return n;
    return fib(n-1) + fib(n-2);
}
int main() {
    constexpr int f5 = fib(5);       // 编译期
    int k; cin >> k;
    int r = fib(k);                  // 运行期也可调用
}

3.3constexpr构造函数(常用于字面类型)

struct Point {
    double x, y;
    constexpr Point(double a, double b) : x(a), y(b) {}
    constexpr double norm2() const { return x*x + y*y; }
};
constexpr Point p{3.0, 4.0};
static_assert(p.norm2() == 25.0);
注意

4.consteval与constinit

consteval int must_be_constexpr(int n) { return n*2; }  // 必须在编译期调用
constinit int g = must_be_constexpr(10);                // g 在编译期初始化

consteval 用于那些希望强制在编译期完成的计算(例如生成编译期表或做元编程检查)。

5. 常见误区与陷阱(constexpr)

6. 实战建议(constexpr)

有关 constexpr 的标准细节参考:cppreferenceconstexpr 条目。

二、explicit深度讲解

1. 含义(核心语义)

explicit 的目的是 禁止编译器执行某些隐式转换,从而避免意外、难以察觉的类型转换错误。它可以修饰:

2. 为什么需要explicit

隐式转换在方便的同时会引发难以发现的逻辑错误、二义性或意外重载匹配,explicit 能把“自动发生”的转换变成“必须写成 T(x)static_cast<T>(x) 的显式转换”,提高代码可读性与安全性。

3.explicit用法示例

3.1 对构造函数

struct A {
    explicit A(int x) : v(x) {}
    int v;
};
void foo(A a) {}
foo(10);         // 错误:A(int) 为 explicit,禁止隐式转换
foo(A(10));      // 正确(显式)
foo(static_cast<A>(10)); // 正确

3.2 对转换运算符(conversion operator)

C++11 起可以写 explicit operator T() const,从而禁止隐式转换为 T

struct S {
    explicit operator bool() const { return true; }
};
S s;
if (s) { }  // 不能:implicit conversion to bool is not allowed?  
           // Actually `if (s)` requires context of boolean; for explicit operator bool, direct-initialization in if condition uses explicit? Explanation below.

说明:explicit operator bool() 的引入是为了替代“safe bool idiom”。explicit 转换运算符不会参与某些隐式转换场景,从而避免意外使用。标准对什么时候允许使用显式转换运算符(例如在 if (expr)static_cast<bool>(expr)、直接初始化等)做了具体规定。详见 cppreference

3.3 C++20 条件explicit(expr)

可以根据模板参数或常量条件使构造函数/转换运算符有条件地显式

template<typename T>
struct Wrapper {
    explicit(sizeof(T) > 4) Wrapper(T);   // C++20: 如果 T 大于4字节,则构造器为 explicit
};

或对转换运算符:

struct X {
    explicit(sizeof(int) <= 4) operator int() const;
};

这种写法让模板库可以更精细控制隐式转换行为。

4. 显式转换运算符的语义细节

5. 常见误用与陷阱(explicit)

6. 推荐实践(explicit)

三、constexpr与explicit的交互要点

struct S {
    constexpr explicit S(int x): v(x) {}
    int v;
};
constexpr S s = S(3); // ok: explicit but direct-initialization

四、实战样例(综合示例)

#include <type_traits>
// C++20 风格:条件 explicit + constexpr + consteval 示范
struct Big {
    int x;
    constexpr explicit Big(int v) : x(v) {}  // constexpr + explicit 构造器
    explicit operator int() const { return x; } // explicit conversion operator
};
consteval int must_be_ctime() { return 42; }  // 强制编译期求值 (C++20)
constinit int g = must_be_ctime();            // 强制常量初始化 (C++20)
static_assert(std::is_same_v<decltype(static_cast<int>(Big(3))), int>); // OK
// auto a = Big(3); // if function takes Big by value, implicit construction not allowed

五、常见问题快速问答

Q:constexpr 函数内部能用循环/分支吗?
A:可以(从 C++14 起放宽),但用于编译期时函数体中的所有操作必须可在编译期执行(不能进行未允许的运行时操作)。

Q:constevalconstexpr 的区别?
A:consteval 强制编译期求值;constexpr 允许编译期也允许运行期调用。

Q:explicit operator 什么时候应该使用
A:当你想阻止类型被无意间隐式转换(尤其是布尔/数值上下文)时应使用 explicit;否则可能引发模糊或错误的重载选择。

六、参考资料

到此这篇关于C++中constexpr 与 explicit关键字使用实战样例的文章就介绍到这了,更多相关C++ constexpr 与 explicit使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文