`constexpr` 和 `#define` 的区别

Difference between `constexpr` and `#define`

所以我阅读了关于什么是 differences between constexpr and const 的有趣答案,但我很好奇 #define 和 constexpr 之间的区别?我觉得 constexpr 只是一个可以选择类型的#define。

使用#define定义的语句称为宏。宏被用于多种用途。

  1. 我们可以使用它们来有条件地编译代码段。
#ifdef ONE
int AddOne(int x) { return x + 1; }

#else
int AddTwo(int x) { return x + 2; }

#endif
  1. 当我们不需要在变量中存储常量时。
#define MAX_BOUND 1000
#define MIN_BOUND 10
  1. 对于我们可以使用宏更改数据类型的地方。
#ifdef USE_WIDE_CHAR
#define TEXT(...)    L##__VA_ARGS__

#else
#define TEXT(...)    __VA_ARGS__

#endif
  1. 根据条件定义关键字。
#ifdef BUILD_DLL
#define DLL_API __declspec(dllexport)

#else
#define DLL_API __declspec(dllimport)

#endif

由于它们是在实际编译阶段之前解决的,我们可以根据某些因素(平台、构建系统、体系结构等)对源代码进行小的改进。

constexpr 本质上声明变量或函数 可以 在编译时解析,但不能保证。

I feel like constexpr is just a #define where the type can be chosen.

这不完全正确。正如我之前所说,因为它们在编译阶段之前就已解决,所以我们可以利用它的一些优势。唯一常见的用途是编译器可以轻松替换为优化的常量值。除此之外,用例也不同。

你说得很对。

#define(也称为 'macro')只是在预处理器阶段发生的文本替换,实际编译器之前。而且明显不是打出来的

constexpr 另一方面, 在实际解析期间发生 。它确实是打字的。 不用说,无论何时何地,使用 constexpr 都会更安全一些。