What are the benefits of constexpr char[] as a cla

2020-07-29 04:30发布

It is more of the rhetorical question (and a rant). Pre-11 every time I had to make a library which exhibited static const char* const (as in static const char* const class_name = "ClassA";) as class members, I knew the library could no longer be header-only – I had to provide a .cpp file with a definition of this variable and its value.

So instead, I had to turn it into the static function name(), returning the pointer.

Then C++11 came, and now I can have static constexpr char[] as my member – and I can even give it a value in my header! But I still have to provide the definition… So I am not excited at all.

Why would that be the case? If constexpr can be evaluated by compiler at compile time, why do I need a definition of it? Why does it have to have linkage at all?

标签: c++ c++11
1条回答
Explosion°爆炸
2楼-- · 2020-07-29 05:13
  • Your are talking of static constexpr, so you have to deal with static keyword
  • Static imposes that you declare it in outside the header because of the one definition rule. This rule means that you cannot declare the same variable more thhan once. If you could declare it in the header and you included the header in two places, you would declare the variable twice.

  • However, as you can do it compile time, you can save a lot of startup time for your program (remember the fibonacci example)

Bottom line: you have the boiring part of the syntax of static variable, but you can save some runtime with it

More details here for the static part here:

Why does constexpr static member (of type class) require a definition?

查看更多
登录 后发表回答