我应该喜欢一个函数中的常量:constexpr const或枚举? [英] Which should I prefer for a constant within a function: constexpr const or enum?

查看:141
本文介绍了我应该喜欢一个函数中的常量:constexpr const或枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于用枚举定义我的常量{my_const = 123; } ,因为在类中,使用 static constexpr 需要在类定义之外的一些代码(请参阅这个问题)。但是 - 在功能体中呢?最近我一直在注意到,他们的功能中只有 constexpr 变量(实际上甚至没有困扰 const ),我想知道我是否是一个愚蠢的人,他的背后是我的

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;
}

所以,我的问题是:在函数体中使用枚举是否有好处而不是constexpr变量?

So, my question is: Is there any benefit to using enum's within function bodies rather than constexpr variables?

推荐答案

您可以意外或有意强制ODR存在 bar 如果它是一个 constexpr int bar = 456; ,这不可能与枚举:int {bar = 456};

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.

例如

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);
}

枚举版本没有编译, constexpr int 一个。一个 constexpr int 可以是一个左值,枚举器(列出的枚举常量之一)不能。

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.

枚举值实际上不是 int ,而 constexpr int 实际上是一个 int 。如果您将其传递给

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.

这篇关于我应该喜欢一个函数中的常量:constexpr const或枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆