On 2022-11-19, aotto1968 <
aott...@t-online.de> wrote:
>
> Hi,
>
> the "_Generic feature looks good and I found a solution:
>
> /// cast a \e known-object into an \RMkNs{ObjectS} reference
> #define MkOBJ_R(x) (_Generic((x),struct MkObjectS *:(*x),default:((*(x)).super.obj)))
> /// cast a \e known-object into an \RMkNs{ObjectS} pointer
> #define MkOBJ(x) (&MkOBJ_R(x))
>
> and now the next problem arrive, this will *NOT* compile with C++.
It's not C++; _Generic is an invention of the ISO C committee, added to
C in the 2011 revision of the standard ("C11").
C and C++ are separately evolving languages. C++ adopts some newer
features from C, but at a relatively glacial pace.
> but C++ say: Why can't I use _Generic in C++ code?
Why can't speak Chinese when ordering in a Greek restaurant?
You need to do:
#ifdef __cpluspuls
#define MkOBJ(x) // .... insert C++ solution here ...
#else
// above _Generic solution
#endif
C++ has compile-time genericity in the form of templates (template
classes, template functions), and supports something called partial
specialization whereby a template can have a different body for
specific combinations of the parameters types.
My C++ is rusty at the moment, but it looks something like:
// Base template, providing default implementation:
template <typename T>
inline MkObjectS *MkOBJ_R(T *ptr)
{
return ptr->super.obj;
}
// Specialization to MkObjectS *
template <>
inline MkObjectS *MkOBJ_R<MkObjectS *>(MkObjectS *ptr)
{
return ptr;
}
Because of the existence of templates, it seems unlikely that C++ will
pick up _Generic. _Generic can be regarded as C's answer to a lack
of templates, for some common situations, like defining type-generic
math routines.
It seems like it might be possible to write some elaborate macros which
provide generic selection in some reasonably convenient syntax, and
which compile to either C11 _Generic or else to a bunch of template
functions.
Ideally the syntax might look like
TYPE_CASE(X, (A, B), (C, D), ...)
Then you just #include the header that gives you this elaborate
macro and use it in C11 or C++ code.