Quick Q: Static constexpr int vs old-fashioned enum: when and why?

Save to:
Instapaper Pocket Readability

Quick A: A static constexpr cannot be used in an ODR context.

Recently on SO:

Static constexpr int vs old-fashioned enum: when and why?

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 returned 1 exit status

However, the true enum always works.

Add a Comment

You must sign in or register to add a comment.

Comments (0)

There are currently no comments on this entry.