在我的 Linux (和 OS X)机器上,iconv()
函数有这样一个原型:
size_t iconv (iconv_t, char **inbuf...
而在 FreeBSD 上看起来是这样的:
size_t iconv (iconv_t, const char **inbuf...
我希望我的 C + + 代码能在这两个平台上构建。对于 C 编译器,为 const char**
参数传递 char**
(反之亦然)通常只会发出一个警告; 但是在 C + + 中,这是一个致命的错误。因此,如果我传递一个 char**
,它不会在 BSD 上编译,如果我传递一个 const char**
,它不会在 Linux/OS X 上编译。如何编写同时在两者上编译的代码,而不必尝试检测平台?
我的一个(失败的)想法是提供一个本地原型,覆盖头部提供的任何内容:
void myfunc(void) {
size_t iconv (iconv_t, char **inbuf);
iconv(foo, ptr);
}
这将失败,因为 iconv
需要 C 连接,并且您不能将 extern "C"
放在函数中(为什么不呢?)
我想到的最好的办法就是把函数指针本身铸造出来:
typedef void (*func_t)(iconv_t, const char **);
((func_t)(iconv))(foo, ptr);
但这有可能掩盖其他更严重的错误。