On my Linux (and OS X) machines, the iconv() function has this prototype:
size_t iconv (iconv_t, char **inbuf...
while on FreeBSD it looks like this:
size_t iconv (iconv_t, const char **inbuf...
I would like my C++ code to build on both platforms. With C compilers, passing a char** for a const char** parameter (or vice versa) typically emits a mere warning; however in C++ it’s a fatal error. So if I pass a char**, it won’t compile on BSD, and if I pass a const char** it won’t compile on Linux / OS X. How can I write code that compiles on both, without resorting to trying to detect the platform?
One (failed) idea I had was to provide a local prototype that overrides any provided by the header:
void myfunc(void) {
size_t iconv (iconv_t, char **inbuf);
iconv(foo, ptr);
}
This fails because iconv needs C linkage, and you cannot put extern "C" within a function (why not?)
The best working idea I’ve come up with is to cast the function pointer itself:
typedef void (*func_t)(iconv_t, const char **);
((func_t)(iconv))(foo, ptr);
but this has the potential to mask other, more serious errors.
If what you want is just to turn a blind eye to some const issues, then you can use a conversion which blurs the distinction, i.e. makes char** and const char** interoperable:
Then later in the program:
sloppy() takes a
char**or aconst char*and converts it to achar**or aconst char*, whatever the second parameter of iconv demands.UPDATE: changed to use const_cast and call sloppy not a as cast.