-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
I am confused about a constexpr function? #22
Comments
请翻回第二章节:
书上给 Literal Type 有非常清楚简洁的定义,Mike Seymour大神说的一点没错,
这个怎么能晕!还是第二章,(每一章节后面都有名词解释,不知道中文版是不是)
这倒是有点接近你说的 1,“hello” 之类的了。。。 举几个例子: constexpr unsigned sz = 42;
string bad[sz]; // constant expression 可以作为数组的下标
sizeof (type); // sizeof 的返回值是 constant expression,所以 size_t 也就是 Literal Type 了。
constexpr size_t sz = sizeof(ia)/sizeof(*ia);
switch(ch) {
case 3.14: // 这里 case 后面跟的,一定是 integral constant expressions 以上都是之前章节的例子,到这一节,又多了一个 constexpr function 返回的也是 constant expression 了。 概念搞清楚了,就会恍然大悟这里一点也不矛盾。 constexpr size_t scale(size_t cnt) { return new_sz() * cnt; }
所以要注意看它的注释:
可能你想问,为啥做了乘法还是 constant expression,打个比方: constexpr size_t sz = 42;
sz * 4; <== 你说这个 expression 在编译期间能否确定值?口算都出来了吧(168)。。。 |
说句题外话: 你如此善于提问(提问水平可与 @Mooophy 相提并论,在此敬佩一下),能否将你 post 到 SO 上的问题,尽量嵌入目前的习题答案里(只需要相关即可),然后可以给我发 pull request. 我觉得可以帮助更多的人。毕竟答案不是目的,好的问题带来好的讨论,能产生更深的理解。 Thx a lot~ 🙇
这个貌似是 Github 的防御机制,避免恶意灌水。解决办法如下:
|
haha , reading this question on SO, I thought it was post by my self... |
C++ is a huge language with quite a lot of features. IMHO, it's quite important to make use of time wisely. So for the feature We can compare To my knowledge, Whereas See? If same time payed on both, one would gain a lot from Well, you would gain a little from As another evidence, Visual Studio has't implemented it at all. Even the vs2015 has only implemented it partially. As a personal suggestion, if @Ocxs has problem following |
@pezy 我比之前更加理解了,但是总感觉没有悟透,所以这个准备暂时放一下。您说的将问题post 到 目前的习题答案里,没问题,那我之前在知乎还有segmentfault上面的提问用不用也贴上去?谢谢您的讲解! |
@Ocxs I'm a student... |
@Ocxs I'm a "worker"....... 😭 🏭 🏭 🏭 🏭
If possible, I'd like to merge it.
Can you see the |
@pezy Thx a lot! |
@pezy Awesome! 👍 |
solution to 10.25
This is question I asked in SO,there are some answers, but I can't understand it .
为了便于清楚的表达我的疑惑之处,我还是用中文描述一下。
书上说
constexpr
函数有几项约定:函数的返回类型及所有形参的类型都得是LiteralType。其实我一直以为LiteralType
就是1
,“hello”
这样的,但是看了那个链接,里面那个Requirements是表达什么意思呢?(英语渣渣没看懂)但是然后他又说允许
constexpr
函数的返回值并非一个常量:然后看了constant expression这个概念,直接把我看晕了,之前以为以为被
const
修饰的表达式即是constant expression
,但看了一下,里面一大堆constant expression
的分类,我就不知道到底什么是constant expression
了。根据 @ Mike Seymour 在评论里说的,
size_t
是LiteralType
,所以函数返回类型是LiteralType
,但是我又搞不明白了,return
这个返回值不是LiteralType
吧,这是怎么回事呢?求指点迷津!另外插一句,是不是一个人在对同一个repository一次最多只能开一个issue?我发现我想重新开一个issue问其他章的问题,直接变成重新编辑这个issue了
The text was updated successfully, but these errors were encountered: