I'm used to definition my constants with enum { my_const = 123; }
enum { my_const = 123; }
, since in classes, using static constexpr
requires some code outside of the class definition (see this question ). But - what about in function bodies? Lately I've been noticing people just having constexpr
variables in their functions (not even bothering to const
them actually), and I was wondering whether I'm a fool who's behind the times with my
int foo(int x)
{
enum : int { bar = 456 };
return x + bar;
}
So, my question is: Is there any benefit to using enum's within function bodies rather than constexpr variables?
You can accidentally or on purpose force ODR-existence of bar
if it was a constexpr int bar = 456;
, this is not possible with enum : int { bar = 456 };
.
This may or may not be an advantage on either side.
For example
int baz(int const* ptr ) {
if (ptr) return 7; return -1;
}
int foo(int x)
{
// enum : int { bar = 456 };
constexpr int bar = 456;
return x + baz(&bar);
}
the enum
version doesn't compile, the constexpr int
one does. A constexpr int
can be an lvalue, an enumerator (one of the listed enum constants) cannot.
The enum values aren't actually an int
, while the constexpr int
is actually an int
. This may matter if you pass it to
template<class T>
void test(T) {
static_assert(std::is_same<T,int>::value);
}
one will pass the test; the other will not.
Again, this could be an advantage, a disadvantage, or a meaningless quirk depending on how you are using the token.
A one-liner based on @Yakk's (but this is my own take):
using enum
-based constants may be necessary if you cannot allow your constant to exist as a "variable" at run time . With an enum, regardless of what you do - it will have no address and no memory space taken up (and not only because of compiler optimizations which may or may not occur).
In other cases there doesn't seem to be a compelling reason to prefer one over the other.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.