让 C 在 _Generic 中生成错误

Sku*_*del 1 c generics macros c11

我一直在研究一些代码(与线性代数相关)。我有多种类型,它们应该能够相互相乘。

我自然地想到“让我们使用 _Generic”来实现这一点。只要参数类型的组合有效,它就可以工作。根据搜索引擎,一些库诉诸于使用虚拟函数的属性来生成错误:

#include "stdio.h"

// Example struct.
typedef struct mat3_s
{
    float m[9];
} mat3;

// Dummy function.
mat3 mult(mat3 const *A, mat3 const *B)
{   
    return *A;
}

mat3 mults(mat3 const *A, float const *B)
{
    return *A;
}

typedef mat3 (*dummyptr)(void *A, void *B);
extern dummyptr INCOMPATIBLE_TYPES() __attribute__((error("Crikey"))); 

#define LMULT(A, B)\
    _Generic((A),\
    mat3: \
        _Generic((B),\
            mat3: mult, \
            float: mults, \
            default: INCOMPATIBLE_TYPES()),\
    default: INCOMPATIBLE_TYPES()) (&(A), &(B))

int main(int argc, char *argv[])
{
    mat3 a = {{0}};
    mat3 b = {{0}};
    mat3 c = LMULT(a, b);

    mat3 d = LMULT(a, "not kosher");

    // Inhibit GCC from optimising away above variables.
    printf("%p %p %p %p\n", &a, &b, &c, &d);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

涉及到的体操就是“INCOMPATIBLE_TYPES”函数。就目前情况而言,它效果不佳(如果有的话)。它只是海湾合作委员会的,而且脆弱,而且……只是不好。

_Pragma("gcc error \"Great heavens\"")也不会工作,因为 GCC 扩展_Pragma为结果宏。这恰好位于_Generic- 表达式内,当然会在稍后阶段进行处理。

我即将放弃,只是给出一些乱码(也称为 C++ 错误报告),希望它能提供足够的信息来说明可能出现的问题。

如果传递两种没有相应函数的类型,是否还有其他人有任何想法如何生成用户足够友好的消息?

Jen*_*edt 6

至少对于您的示例来说,解决方案非常简单,省略default零件即可。然后编译器将产生类型不匹配的错误。