使用静态成员函数替换静态const成员的优点[重复](Advantage of replacing static const members with static member functions

编程入门 行业动态 更新时间:2024-10-27 18:19:23
使用静态成员函数替换静态const成员的优点[重复](Advantage of replacing static const members with static member functions [duplicate])

这个问题在这里已有答案:

static constexpr变量vs函数 1回答

我从程序员那里得到了这样的代码,我非常尊重:

class BigClass { using MyId = uint32_t; static constexpr MyId INVALID_ID() { return std::numeric_limits<MyId>::max();}; class SmallClass { /* Constructor, etc. */ MyId id = INVALID_ID(); /* Default value */ }; };

将INVALID_ID()定义为函数而不是静态const变量有明显的优势吗?

静态constexpr变量vs函数的问题与我的问题完全相同(我使用uint32_t作为示例,但我发现其他类型的问题也很有趣)。 但是,我对这个问题的答案不满意。 在阅读了这里的一些答案后,我相信使用函数比使用简单模板的能力更有优势。

This question already has an answer here:

static constexpr variable vs function 1 answer

I came across code like this from a programmer I highly respect:

class BigClass { using MyId = uint32_t; static constexpr MyId INVALID_ID() { return std::numeric_limits<MyId>::max();}; class SmallClass { /* Constructor, etc. */ MyId id = INVALID_ID(); /* Default value */ }; };

Is there any obvious advantage to defining INVALID_ID() as a function instead of as a static const variable?

The question static constexpr variable vs function is precisely the same question I had (I used uint32_t as an example, but I find the question interesting for other types as well). However, I am not satisfied with the answer to that question. After reading some of the answers here, I believe there are more advantages to using functions than the ability to be easily templated.

最满意答案

一个原因是在这种形式中,不需要在类外定义静态成员,这在类在头部内实现的情况下是不合需要的。

第二个原因是可扩展性,您可能有一天希望您的无效ID在其初始化中执行其他constexpr逻辑,而不是调用一个constexpr函数,如max

One reason is that in this form, there is no need for defining the static member outside the class, which in cases where the class is implemented inside a header can be undesirable.

A second reason is extensibility, you could one day want your invalid ID to do some other constexpr logic in its initialization, other than calling one constexpr function like max

更多推荐

本文发布于:2023-08-02 06:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1370048.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   成员   函数   优点   const

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!