_Generic 结合可变参数函数?
_Generic combined with variadic function?
在 C11 中,我可以创建一个原型如下所示的函数:
void myVaFunc(const char* const conv, ...);
我可以 运行 像这样:
myVaFunc("ici", 1, "test", 2);
该函数会知道(在解析第一个参数之后)还有 3 个附加参数(4 个是初始参数),其类型分别为 int
、string
(字符指针)和 int
。简单,但不是很优雅。最近我了解到 _Generic
关键字,它允许在编译时导出变量的类型。我开始怀疑是否有一种方法可以结合可变参数功能(不再起作用,因为它总是需要第一个静态参数)和 _Generic
功能。为什么?为了删除第一个参数,它告诉函数如何解析其他参数。能有这样调用的宏吗?
MYVAFUNC(1, "test", 2);
并以与之前所述相同的方式工作myVaFunc
?
我现在考虑了一段时间,但还是想不通。
这绝对是可能的,但 AFAIK,它需要一些重要的宏魔法
(并且很难让它适用于无限数量的参数)。
在我的项目中,我有一个 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 行神秘的代码,大部分是生成的代码。
这是生成它并在上面发布的 main 上测试运行它的脚本:
#!/bin/sh -eu
bx_def_BX_argc() #Define an arg-counting macro for Max 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="" 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,
您可以将上面的 foreach 生成的逗号表达式替换为以下形式的表达式语句(非标准但常见的 C 扩展):
({
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 基于逗号的特殊情况。)
在 C11 中,我可以创建一个原型如下所示的函数:
void myVaFunc(const char* const conv, ...);
我可以 运行 像这样:
myVaFunc("ici", 1, "test", 2);
该函数会知道(在解析第一个参数之后)还有 3 个附加参数(4 个是初始参数),其类型分别为 int
、string
(字符指针)和 int
。简单,但不是很优雅。最近我了解到 _Generic
关键字,它允许在编译时导出变量的类型。我开始怀疑是否有一种方法可以结合可变参数功能(不再起作用,因为它总是需要第一个静态参数)和 _Generic
功能。为什么?为了删除第一个参数,它告诉函数如何解析其他参数。能有这样调用的宏吗?
MYVAFUNC(1, "test", 2);
并以与之前所述相同的方式工作myVaFunc
?
我现在考虑了一段时间,但还是想不通。
这绝对是可能的,但 AFAIK,它需要一些重要的宏魔法 (并且很难让它适用于无限数量的参数)。
在我的项目中,我有一个 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 行神秘的代码,大部分是生成的代码。
这是生成它并在上面发布的 main 上测试运行它的脚本:
#!/bin/sh -eu
bx_def_BX_argc() #Define an arg-counting macro for Max 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="" 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, 您可以将上面的 foreach 生成的逗号表达式替换为以下形式的表达式语句(非标准但常见的 C 扩展):
({
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 基于逗号的特殊情况。)