Please note, answer below is not applicable for C++ 17 and later.
There will be no noticeable difference for integral constants when used like this.
However, enum
is actually better, because it is a true named constant. constexpr
integral constant is an object which can be, for example, ODR-used – and that would result in linking errors.
#include <iostream>
struct T {
static constexpr int i = 42;
enum : int {x = 42};
};
void check(const int& z) {
std::cout << "Check: " << z << "\n";
}
int main() {
// check(T::i); // Uncommenting this will lead to link error
check(T::x);
}
When check(T::i)
is uncommented, the program can not be linked:
/tmp/ccZoETx7.o
: In function `main
‘:ccc.cpp
🙁.text+0x45
): undefined
reference to `T::i
‘collect2
: error:ld
returned1
exit status
However, the true enum
always works.