Home > Net >  Is it possible to have a type alias that can't be converted to the base type?
Is it possible to have a type alias that can't be converted to the base type?

Time:11-10

I have a typedef like this for example:

typedef char * cstring;

Is it possible to make cstring not implicitly convertible to char * (for example with attributes), so for example if I have a function like this:

int string_compare( cstring rhs, cstring lhs );

I could call it like this:

cstring a = [...], b = [...];
string_compare(a, b);

but not like this:

char * a = [...], * b = [...]
string_compare(a, b);

I accept all solutions even if not standard (GCC only for example)

Explication of why I want to do this: I have a hidden struct:

struct s_cstring_int
{
  int length;
  int capacity;
  char data[];
}

In my function string_new I allocate one and return only the data pointer, so the string can be accessed with operator[]

CodePudding user response:

Typedef pointers are very confusing. Do not use typedef pointers.

Is it possible to make cstring not implicitly convertible to char *

Sure, just make it a struct.

typdef struct cstring_s {
   char *str;
} cstring;

Is it possible to have a type alias that can't be converted to the base type?

No, a type alias is just that - an alias.

  • Related