小编cat*_*cat的帖子

是否可以用C11的_Generic实现GNU C的typeof(x)?

要在C和C++中编译一些代码,我在以下几个地方使用它:

#ifdef __cplusplus 
    #define typeof(x) decltype(x) // works ok in most cases, except C++ reference types
#endif 

char* a = (typeof(a)) malloc(4);
Run Code Online (Sandbox Code Playgroud)

在C中,这将编译到char* a = (char *) malloc(4)完全不必要的强制转换的位置,但是在C++ void *中不会隐式提升,char *如果不存在强制转换则会发出错误.

当我可以-std=gnu11在GCC或Clang上编译时,这也是一样,但当我想将我的代码编译为ISO C11时呢?我以为我可以用C11 _Generic来实现typeof(x)一些类型:

#define gettype(x) _Generic((x), \
  short:       (short ), \
  char:        (char  ), \
  char*:       (char *), \
  default:     (void *)  )

int main (void) {
  short a = (gettype(a)) 1;

  return a;
}
Run Code Online (Sandbox Code Playgroud)

但无论gettype(x)a …

c generics gcc gnu c11

7
推荐指数
1
解决办法
1054
查看次数

为什么内联if语句的平均值至少比其他类型的if少三分之一?

考虑以下Perl 6脚本框架:

my regex perlish    { .*[ea]?[ui]? rl $ }
my Str @words = '/usr/share/dict/words'.IO.lines;

for @words -> $word {
    ...
}
Run Code Online (Sandbox Code Playgroud)

来自perl6网站的例子中这个问题代码的基本思想.

/usr/share/dict/words是间接的象征性链接/usr/share/dict/american-english.它长99,171行,有一个字/行.

为了比较,Python 3在总共32秒内执行以下100个循环:这只是0.32942秒/循环.1

以下是我尝试用代替存根代码的内容,其基准时间如下所示:

  • "内联" if- 100个循环,平均9.74219s /循环,总共16分14.219s

    say "$word probably rhymes with Perl" if $word ~~ /<perlish>/;
    say "$word is a palindrome" if $word eq $word.flip && $word.chars > 1;
    
    Run Code Online (Sandbox Code Playgroud)
  • 短路(非三元) - 10个回路,平均6.1925s /回路,标准化为总计+/- 10.3分钟

    $word eq $word.flip  && $word.chars > 1 && say "$word is …
    Run Code Online (Sandbox Code Playgroud)

optimization perl6

6
推荐指数
1
解决办法
234
查看次数

如何停止递归?

代码的出现第1天需要以一种或那种形式循环一长串括号等((((())(())(((()))((.这个想法是(上升到一层,)下到一层,目标是打印

  1. 字符串中第一个索引,其中楼层编号为负数
  2. 找到字符串结尾时的最后一层.

使用for循环的命令式解决方案很简单(以Python为例):

def main():
    flr = 0
    basement = False
    for idx, elt in enumerate(text):
        flr += {
            "(": 1,
            ")": -1
        }.get(elt)

        if flr < 0 and not basement:
            print("first basement pos:", idx + 1)
            basement = True

    print("final floor:", flr)
Run Code Online (Sandbox Code Playgroud)

递归函数解决方案稍微复杂一点,但仍然不太难.

def worker(flr, txt, idx, basement):
    flr += {"(": 1, ")": -1}[ txt[0] ]

    if not (len(txt) - 1): return flr

    if flr < 0 and not basement:
        print("first …
Run Code Online (Sandbox Code Playgroud)

recursion functional-programming declarative factor-lang

6
推荐指数
1
解决办法
227
查看次数

设置UTF-8语言环境后使用fgetws?

GCC 4.8,5.1,6.2和3.8.1锵在Ubuntu 16.10使用-std=c11,-std=c++11,-std=c++14,和-std=c++17都表现出使用时,这种怪异的行为fgetws(buf, (int) bufsize, stdin)setlocale(LC_ALL, "any_THING.utf8");.

示例程序:

#include <locale.h>
#include <wchar.h>
#include <stdlib.h>
#include <stdio.h>

int main(const int argc, const char* const * const argv) {
  (void) argc;

  setlocale(LC_ALL, argv[1]);

  const size_t len = 3;

  wchar_t *buf = (wchar_t *) malloc(sizeof (wchar_t) * len),
         *stat = fgetws(buf, (int) len, stdin);

  wprintf(L"[%ls], [%ls]\n", stat, buf);

  free(buf);

  return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

Casting malloc仅适用于C++ - compat.

像这样编译:cc -std=c11 fg.c …

c glibc wchar-t wchar setlocale

6
推荐指数
1
解决办法
298
查看次数

向 http.server.BaseHTTPRequestHandler 的子类添加一个新的实例变量

我希望能够将实例变量添加到我的http.server.BaseHTTPRequestHandler子类中。

这是我的代码:

from http.server import BaseHTTPRequestHandler, HTTPServer
import urllib


class Server(BaseHTTPRequestHandler):

    def __init__(self, request, client_addr, server):
        super().__init__(request, client_addr, server)
        self.pathobj = urllib.parse.urlparse(self.path)

    def do_HEAD(self):
        self.send_response(200)

    def do_GET(self):
        print(self.pathobj)
        self.send_response(200)
        self.end_headers()

    def do_POST(self):
        print(self.pathobj)
        self.send_response(405)
        self.end_headers()   

def run(server_class=HTTPServer, handler_class=Server, port=8080):
    server_address = ("", port)
    httpd = server_class(server_address, handler_class)

    print("Starting httpd on port {}...".format(port))

    httpd.serve_forever()

if __name__ == "__main__":
    run()
Run Code Online (Sandbox Code Playgroud)

我希望能够访问每个类方法中ParseResult返回的对象,urllib.parse.urlparse而无需在每个类方法self.pathobj = urllib.parse.urlparse(self.path)的开头重写。

上面的代码不起作用 - 当do_GET或被do_POST调用时,它会抱怨'Server' object has no …

http python-3.x basehttprequesthandler

6
推荐指数
1
解决办法
927
查看次数

如果语句中的if语句在语法上是否明确无误?

我不太了解C,但我理解基础知识,据我所知:

int main() {
  if (1 == 1) printf("Hello World!\n");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

int main() {
  if (1 == 1) 
    printf("Hello World!\n");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

int main() {
  if (1 == 1) {
    printf("Hello World!\n");
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

都精确地在语法上是等价的.声明是真的; 字符串打印; 大括号(显然)是可选的.

有时,特别是在SO上,我看到如下内容:

int main() {
  if (1 == 1)
    printf("one is one\n");
  printf("is this inside the if statement??/who kn0WS\n");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

通过CodeGolf赋予的权力,我被引导相信C是与空白无关的; 词法分析器将标记分解为它们的组成部分并剥离字符串外的空格.

(我的意思是,整个原因分号-上每个语句,事情是这样的解析器可以剥离\n,\t,文字空间,还知道每个语句结束吧?)

那么,如果要忽略空格,如何才能明确地解析前一段代码(或者有人可以提出一个更好的例子)?

如果C程序员想要用依赖于空白的Pythonic语法编写,他们为什么要编写C语言,为什么在C语言教学的地方教它可以写出像这样的词汇模糊(对我来说,程序员和计算机)这样的语句?

c syntax lexical-analysis

5
推荐指数
2
解决办法
206
查看次数

如何让 Perl6 (MoarVM / Rakudo) 警告所有缺少的分号?

在 Perl 5 中,最好使用

use strict;
use warnings;
Run Code Online (Sandbox Code Playgroud)

要求编译器抱怨缺少分号、未声明的变量等。

Perl 社区的公民在这里通知我默认情况下Perl 6 uses strict,在测试后似乎是这种情况。

块中的最后一条语句不需要分号,但是如果我稍后扩展块,当我的代码不起作用时我会很懊恼,因为它是同一个块(而且我希望到处都有分号,因为它是,就像,一致和东西)。

我的假设是 Perl 6 甚至不查看块中最后一条语句的分号,但我仍然很好奇:有没有办法让它更严格?

raku

5
推荐指数
1
解决办法
104
查看次数

我可以请一个ArrayOutOfBoundsException吗?

在Python中,如果使用越界键/索引索引集合结构,则会在面部中获得一记:

>>> [1, 2, 3][9]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

这是一个例外; 它派生自BaseException,未能处理一个会导致我的程序崩溃,这几乎总是我想要的.


Perl 5和6的列表索引似乎并不关心越界索引:

$ perl6
> my @l = (1..4);
[1 2 3 4]
> say @l[2];
3
> say @l[9];
(Any)
> print @l[9];                                                                                                          
Use of uninitialized value @l of type Any in string context
<snip>    
True
> my $x = @l[9]; # even assignment doesn't error! who decided this was okay!?
> say …
Run Code Online (Sandbox Code Playgroud)

perl perl6

5
推荐指数
3
解决办法
775
查看次数

当范围反转时为什么是range_iterator?

我可以下标一个range对象:

>>> r = range(4)
>>> r 
range(0, 4)
>>> r[3]
3
>>> for i in r:
    print(i)

0
1
2
3
>>> list(r)
[0, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

但是,如果我调用reversed同一个range对象:

>>> r = reversed(range(4))
>>> r
<range_iterator object at memaddr>
>>> for i in r:
    print(i)
3
2
1
0
>>> r[3]
TypeError: 'range_iterator' object is not subscriptable         # ?
>>> range(r)
TypeError: 'range_iterator' cannot be interpreted as an integer # ?
>>> list(r)
[] …
Run Code Online (Sandbox Code Playgroud)

range python-3.x

5
推荐指数
2
解决办法
5142
查看次数

明确命名的返回值?

在Go(和G ++?)中,以下是一个常见的习语:

func sqr(x int) (n int, err error) {
    n = x * x
    err = nil
    return
}
Run Code Online (Sandbox Code Playgroud)

(n int, err error)明确列举了返回值的名称和类型.在我看来,这有很多优点,我喜欢它.


在Perl 6中,我们可以:

my sub sqr (Int:D $x) returns Int:D {
    $x ** 2;
}
Run Code Online (Sandbox Code Playgroud)

返回是隐式的,这让我有点不舒服(我们可以明确表示return),但你可能会注意到指定了返回类型(因为它已被D定义).

不出所料,没有明显的方法可以通过名称显式返回值,但我很好奇,因为Perl(尤其是6)在各方面都可以进行广泛修改,如果有办法实现这一点的话.1


1然而,它可能是hacky,但太过于hacky而且我会避免将它用于"真实"的东西.

return-value perl6

4
推荐指数
1
解决办法
247
查看次数