Skip to content

Instantly share code, notes, and snippets.

@mattiasgustavsson
Last active April 2, 2025 15:22
Show Gist options
  • Save mattiasgustavsson/904ca536d16310f2d96742f895af7a24 to your computer and use it in GitHub Desktop.
Save mattiasgustavsson/904ca536d16310f2d96742f895af7a24 to your computer and use it in GitHub Desktop.
// In C, a void* can be implicitly cast to any other kind of pointer, while in C++ you need an explicit cast. In most
// cases, the explicit cast works for both C and C++, but if we consider the case where we have nested structs, then
// the way you refer to them differs between C and C++ (in C++, `parent_type::nested_type`, in C just `nested_type`).
// In addition, with the automatic cast in C, it is possible to use unnamed nested structs and still dynamically
// allocate arrays of that type - this would be desirable when the code is compiled from C++ as well.
// This VOID_CAST macro allows for automatic cast from void* in C++. In C, it does nothing, but for C++ it uses a
// simple template function to define a cast-to-anything operator.
// Use like this:
// struct {
// struct {
// int x;
// } *nested;
// } parent;
// parent.nested = VOID_CAST( malloc( sizeof( *parent.nested ) * count ) );
#ifdef __cplusplus
struct void_cast {
inline void_cast( void* x_ ) : x( x_ ) { }
inline void_cast( void const* x_ ) : x( (void*) x_ ) { }
template< typename T > inline operator T() { return (T)x; } // cast to whatever requested
void* x;
};
#define VOID_CAST( x ) void_cast( x )
#else
#define VOID_CAST( x ) x
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment