在我看来,拥有一个“总是返回5的函数”是破坏或冲淡了“调用函数”的含义。这肯定是有原因的,或者需要这种功能,否则它就不会出现在C++11中,为什么会出现呢?
// preprocessor.
#define MEANING_OF_LIFE 42
// constants:
const int MeaningOfLife = 42;
// constexpr-function:
constexpr int MeaningOfLife () { return 42; }在我看来,如果我写了一个返回文字值的函数,然后我进行了代码审查,有人会告诉我,我应该声明一个常量值,而不是写return 5。
发布于 2011-01-21 00:20:06
constexpr函数真的很好,而且是对c++的一个很好的补充。然而,你是对的,它解决的大多数问题都可以用宏来处理。
但是,constexpr的一个用法没有与C++03等效的类型化常量。
// 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;https://stackoverflow.com/questions/4748083
复制相似问题