_Generic与可变参数函数结合起来呢?

问题描述 投票:2回答:1

在C11,我可以创建一个函数原型是这样的,其中:

void myVaFunc(const char* const conv, ...);

我可以这样运行:

myVaFunc("ici", 1, "test", 2);

该函数将知道与类型因此intstring(字符指针)和int(后解析第一参数),有3个额外的参数(4与初始的一个)。容易,但不是很优雅。最近,我已经了解了_Generic关键字,它允许在编译时导出一个变量的类型。我开始怀疑或者有一种方法,以一个可变功能结合起来(不再发挥作用,因为它总是需要第一静态参数)和_Generic功能。为什么?为了去除第一个参数,它告诉函数如何解析他人。宏,这将被称为像这样能够存在?

MYVAFUNC(1, "test", 2);

而在相同的工作方式如前所述myVaFunc

我现在思考了一段时间,但无法弄清楚它要么是可能的。

c variadic-functions c11
1个回答
4
投票

这绝对是可能的,但据我所知,它需要一些平凡的宏观魔术(和它的困难,使其为无限数量的参数工作)。

在项目中,我有一个BX_foreachc(What,...)宏,允许您使用实现它:

#include <stdio.h>
#define MYVAFUNC(...) /*replace puts with the actual consumer of the generated format string*/ \
    (MYVAFUNC__ptr=MYVAFUNC__buf, \
     BX_foreachc(MYVAFUNC__append,__VA_ARGS__), \
     *MYVAFUNC__ptr=0, \
      puts(MYVAFUNC__buf))
//impl.:
char MYVAFUNC__buf[128]; 
char *MYVAFUNC__ptr = MYVAFUNC__buf;
#define MYVAFUNC__append(X) *MYVAFUNC__ptr++ = _Generic(X,char*:'c',int:'i')

int main(void)
{
    MYVAFUNC(1,"foo",1,2,"bar",1,2,3) ; 
    //generates and consumes "iciiciii" and returns the return value of the consumer
}

有问题的部分可能是我的实现BX_foreachc(有多达127参数的支持),大约是140的神秘,主要是生成的代码行。

下面是它生成和测试运行它在脚本上面贴主:

#!/bin/sh -eu
bx_def_BX_argc() #Define an arg-counting macro for Max $1 args (incl) #{{{
{
    local max_args=${1:-128} i
    printf '#define BX_argc(...) BX_argc_(X,##__VA_ARGS__) //{{{\n'
    printf '#define BX_argc_(...) BX_argc__(,##__VA_ARGS__,'
    i=$max_args; while [ $i -gt 0 ]; do printf $i,; i=$((i-1)); done
    printf '0,0)\n'
    printf '#define BX_argc__(_,'
    while [ $i -le $max_args ]; do printf _$i,; i=$((i+1)); done
    printf 'Cnt,...) Cnt //}}}\n'
} #}}}
bx_def_BX_foreach_() #{{{
{
    local Comma="$1" Max="${2:-128}"
    if [ -z "$Comma" ]; then
        echo "#define BX_foreachc_1(What, x, ...) What(x)"
    else
        echo "#define BX_foreach_1(Join, What, x, ...) What(x)"
    fi
    i=2; while [ $i -lt $Max ]; do
        if [ -z "$Comma" ]; then
            printf '#define BX_foreach_%d(Join,What,x,...) What(x) Join BX_paste(BX_foreach_%d(Join, What, __VA_ARGS__))\n' \
              $i $((i-1));
        else
            printf '#define BX_foreachc_%d(What,x,...) What(x) , BX_paste(BX_foreachc_%d(What, __VA_ARGS__))\n' \
              $i $((i-1));
        fi
    i=$((i+1)); done
} #}}}
{
cat <<EOF
#define BX_foreach(Join,What, ...) BX_foreach_(BX_argc(__VA_ARGS__), Join, What, __VA_ARGS__)
#define BX_foreachc(What, ...) BX_foreachc_(BX_argc(__VA_ARGS__), What, __VA_ARGS__)
#define BX_cat(X,...)  BX_cat_(X,__VA_ARGS__) //{{{
#define BX_cat_(X,...) X##__VA_ARGS__ //}}}
#define BX_paste(X) X

///
#define BX_foreach_(N, Join, What, ...) BX_paste(BX_cat(BX_foreach_, N)(Join, What, __VA_ARGS__))
#define BX_foreachc_(N,  What, ...) BX_paste(BX_cat(BX_foreachc_, N)( What, __VA_ARGS__))
EOF

#define BX_argc(...) BX_argc_(X,##__VA_ARGS__)
bx_def_BX_argc
bx_def_BX_foreach_ ''
bx_def_BX_foreach_ 1
} > foreach.h

cat > main.c <<'EOF'
#include "foreach.h" //generated header implementing BX_foreachc
#include <stdio.h>
#define MYVAFUNC(...) /*replace puts with the actual consumer of the generated format string*/ \
    (MYVAFUNC__ptr=MYVAFUNC__buf, \
     BX_foreachc(MYVAFUNC__append,__VA_ARGS__), \
     *MYVAFUNC__ptr=0, \
      puts(MYVAFUNC__buf))
//impl.:
char MYVAFUNC__buf[128]; 
char *MYVAFUNC__ptr = MYVAFUNC__buf;
#define MYVAFUNC__append(X) *MYVAFUNC__ptr++ = _Generic(X,char*:'c',int:'i')

int main(void)
{
    MYVAFUNC(1,"foo",1,2,"bar",1,2,3) ; 
    //generates and consumes "iciiciii" and returns the return value of the consumer
}
EOF

#compile and test-run
gcc main.c
./a.out

如果你想防止溢出127最大参数数量,你可以替换形式的表达式语句(非标准,但共同的C扩展)以上的foreach生成的逗号表达式:

({ 
    char buf[128];
    char *p=buf, *e = buf+sizeof(buf)-1;

    //foreach X:
        if(*p==e) return FAIL; else *p = _Generic(X,char*:'c', int:'i');
    *p = 0;
    puts(buf);
 })

一个更好的方式来处理,这可能是完全放弃格式字符串的,而不是产生像

do{
    //foreach X:
        if(FAILS(_Generic(X,char*: consume_str, int: consume_int)(X))) return FAIL;
}while(0);

例如,工作代码(没有非标准C的特征):

#include <stdio.h>
#include "foreach.h"
#define FAILS(X) (0>(X))
#define FAIL (-1)
int consume_int(int X){ return printf("%d\n", X); }
int consume_str(char const* X){ return puts(X); }

#define MYVAFUNC(...) do{ BX_foreach(;,CONSUME_ARG,__VA_ARGS__); }while(0);
#define CONSUME_ARG(X) if(FAILS(_Generic(X, char*: consume_str, int:consume_int)(X)))
int main(void)
{
    MYVAFUNC(1,"foo",1,2,"bar",1,2,3) ; 
}

(注意,这里使用BX_foreach(使用自定义木匠宏,在我的情况下,它;),而不是基于BX_foreachc逗号特殊情况。)

© www.soinside.com 2019 - 2024. All rights reserved.