Skip to content

Commit 12eddc4

Browse files
authored
Add C++ support (#94)
* Add C++ support To be portable across C and C++ cvector needs only a couple of changes where C++ needs explicit casts. A macro cvector_typeof is made to cast in C++ and do nothing in C and it is applied in needed places * Get rid of type traits std::remove_reference can be replaced with just taking an address of the first element
1 parent a3b21d7 commit 12eddc4

1 file changed

Lines changed: 27 additions & 2 deletions

File tree

cvector.h

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,31 @@ typedef struct cvector_metadata_t {
6262
cvector_elem_destructor_t elem_destructor;
6363
} cvector_metadata_t;
6464

65+
/* C++ requires explicit casts between pointer types when C does not.
66+
* cvector_typeof either does nothing since typeof in C was introduced
67+
* too late (only in C23) and C can happily cast implicitly, or returns
68+
* the type of a given expression depending on the language
69+
*/
70+
#ifdef __cplusplus
71+
/* When macros are used, arguments are often get enclosed in
72+
* parentheses. When decltype() gets a parenthesized expression, it
73+
* also makes the type a reference and C++ compiler complains about
74+
* this during the cast. Taking an address of the first element removes
75+
* the reference part
76+
*/
77+
/**
78+
* @brief cvector_typeof - Return a type of the expression
79+
* @param expr An expression to examine
80+
*/
81+
#define cvector_typeof(expr) decltype(&(expr)[0])
82+
#else
83+
/**
84+
* @brief cvector_typeof - Stub macro returning void *
85+
* @param _ Stub parameter
86+
*/
87+
#define cvector_typeof(_) void *
88+
#endif
89+
6590
/**
6691
* @brief cvector_vector_type - The vector type used in this library
6792
* @param type The type of vector to act on.
@@ -407,11 +432,11 @@ typedef struct cvector_metadata_t {
407432
void *cv_grow_p1__ = cvector_vec_to_base(vec); \
408433
void *cv_grow_p2__ = cvector_clib_realloc(cv_grow_p1__, cv_grow_sz__); \
409434
cvector_clib_assert(cv_grow_p2__); \
410-
(vec) = cvector_base_to_vec(cv_grow_p2__); \
435+
(vec) = (cvector_typeof(vec))cvector_base_to_vec(cv_grow_p2__); \
411436
} else { \
412437
void *cv_grow_p__ = cvector_clib_malloc(cv_grow_sz__); \
413438
cvector_clib_assert(cv_grow_p__); \
414-
(vec) = cvector_base_to_vec(cv_grow_p__); \
439+
(vec) = (cvector_typeof(vec))cvector_base_to_vec(cv_grow_p__); \
415440
cvector_set_size((vec), 0); \
416441
cvector_set_elem_destructor((vec), NULL); \
417442
} \

0 commit comments

Comments
 (0)