作为类成员的constexpr char []有什么好处? [英] What are the benefits of constexpr char[] as a class member?

查看:116
本文介绍了作为类成员的constexpr char []有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更多的是反问的问题(和咆哮声)。每次Pre-11时,我必须制作一个展示 static const char * const 的库(如 static const char * const class_name = ClassA ; )作为类成员,我知道该库不再是仅标头的了–我必须提供一个 .cpp 文件,其定义为这个变量及其值。

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.

因此,我不得不将其转换为 static 函数 name(),返回指针。

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

然后C ++ 11出现了,现在我可以拥有作为成员的静态constexpr char [] –甚至可以在标头中给它一个值!但是我仍然必须提供定义……所以我一点都不兴奋。

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.

为什么会这样呢?如果 constexpr 可以在编译时由编译器求值,为什么我需要对其进行定义?为什么它必须完全具有链接?

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?

推荐答案


  • 您在谈论静态 constexpr,因此您必须处理静态关键字

  • 由于一个定义规则,静态表示您必须在标头外部声明它。此规则意味着您一次只能声明同一变量。如果可以在标头中声明它,并且将标头包含在两个位置,则将变量声明两次。

    • 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

      此处为 static 部分的更多详细信息:

      More details here for the static part here:

      为什么constexpr静态成员(类型类型)需要定义?

      这篇关于作为类成员的constexpr char []有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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