Which should I prefer for a constant within a function: constexpr const or enum?

陌路散爱 提交于 2019-12-23 07:46:01

问题


I'm used to definition my constants with 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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/43595668/which-should-i-prefer-for-a-constant-within-a-function-constexpr-const-or-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!