首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >什么时候应该在C++11中使用constexpr功能?

什么时候应该在C++11中使用constexpr功能?
EN

Stack Overflow用户
提问于 2011-01-20 22:07:06
回答 14查看 130K关注 0票数 365

在我看来,拥有一个“总是返回5的函数”是破坏或冲淡了“调用函数”的含义。这肯定是有原因的,或者需要这种功能,否则它就不会出现在C++11中,为什么会出现呢?

代码语言:javascript
运行
复制
// preprocessor.
#define MEANING_OF_LIFE 42

// constants:
const int MeaningOfLife = 42;

// constexpr-function:
constexpr int MeaningOfLife () { return 42; }

在我看来,如果我写了一个返回文字值的函数,然后我进行了代码审查,有人会告诉我,我应该声明一个常量值,而不是写return 5。

EN

Stack Overflow用户

发布于 2011-01-21 00:20:06

constexpr函数真的很好,而且是对c++的一个很好的补充。然而,你是对的,它解决的大多数问题都可以用宏来处理。

但是,constexpr的一个用法没有与C++03等效的类型化常量。

代码语言:javascript
运行
复制
// This is bad for obvious reasons.
#define ONE 1;

// This works most of the time but isn't fully typed.
enum { TWO = 2 };

// This doesn't compile
enum { pi = 3.1415f };

// This is a file local lvalue masquerading as a global
// rvalue.  It works most of the time.  But May subtly break
// with static initialization order issues, eg pi = 0 for some files.
static const float pi = 3.1415f;

// This is a true constant rvalue
constexpr float pi = 3.1415f;

// Haven't you always wanted to do this?
// constexpr std::string awesome = "oh yeah!!!";
// UPDATE: sadly std::string lacks a constexpr ctor

struct A
{
   static const int four = 4;
   static const int five = 5;
   constexpr int six = 6;
};

int main()
{
   &A::four; // linker error
   &A::six; // compiler error

   // EXTREMELY subtle linker error
   int i = rand()? A::four: A::five;
   // It not safe use static const class variables with the ternary operator!
}

//Adding this to any cpp file would fix the linker error.
//int A::four;
//int A::six;
票数 20
EN
查看全部 14 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4748083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档