RE: [Dev-C++] ANSI C++ forbids implicit conversion from `void *' in argument passing
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Ioannis V. <no...@ya...> - 2002-02-10 23:08:25
|
> -----Original Message-----
> From: dev...@li...
> [mailto:dev...@li...] On Behalf
> Of Ioannis Vranos
> Sent: Monday, February 11, 2002 12:57 AM
> To: Dev-C++
> Subject: RE: [Dev-C++] ANSI C++ forbids implicit conversion
> from `void *' in argument passing
>
>
> In C++ a void * can not be assigned directly in any pointer
> type without casting, e.g. the result of malloc() needs
> casting in C++. void * is used a lot in C to emulate generic
> programming with poor abilities in the particular area, that
> is to write functions that do things on various types of
> variables using ancient non type safe techniques. C++ has
> built in support for generic programming with the best
> possible way, templates. Templates arre both time efficient,
> space efficient if you use specializations where is needed
> and type-safe at the same time. E.g. consider the following
> C++ C-style code:
>
> void *add(void *p1, void *p2, const char *type)
> {
> if(strcmp(type, "int")
> {
> if(int *resul=(char *)malloc(sizeof(int)))
> {
> *result=(int *)p1+(int *)p2;
> return result;
> }
>
> else if(strcmp(type, "float")
> // Pain goes on...
>
> }
>
>
> Consider the template alternative:
>
> template <class T>
> inline T add(T a, T b)
> {
> return a+b;
> }
>
>
> It is both type safe and maximally efficient.
>
>
> So better use templates in the place where you use void * for
> generic programming.
Tonight i have drunk a bit wine hic, but i just realised that the
original question was about some API. Anyway i made mistakes! in the
previous email in the C-style implementation so here is the correct one:
void *add(void *p1, void *p2, const char *type)
{
if(!strcmp(type, "int"))
{
if(int *result=(int *)malloc(sizeof(int)))
{
*result=*(int *)p1+*(int *)p2;
return result;
}
}
else if(!strcmp(type, "float")
// Pain goes on...
}
And the template alternative is better written:
template <class T>
inline T add(const T &a, const T &b)
{
return a+b;
}
Now if i made more mistakes, sorry fellows it is the wine. :)
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.d2g.com
* Alternative URL: http://run.to/noicys
|