这个问题在这里已有答案:
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 answerI 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
更多推荐
发布评论