【发布时间】:2011-12-12 20:54:41
【问题描述】:
我有以下代码用于“安全”strncpy()——基本上,它的包装器自动为字符串缓冲区采用固定的数组大小,因此您不必做额外的工作来传递它们(而且这种方便更安全因为您不会意外地为固定数组缓冲区输入错误的大小)。
inline void MySafeStrncpy(char *strDest,size_t maxsize,const char *strSource)
{
if(maxsize)
{
maxsize--;
strncpy(strDest,strSource,maxsize);
strDest[maxsize]=0;
}
}
inline void MySafeStrncpy(char *strDest,size_t maxDestSize,
const char *strSource, size_t maxSourceSize)
{
size_t minSize=(maxDestSize<maxSourceSize) ? maxDestSize:maxSourceSize;
MySafeStrncpy(strDest,minSize,strSource);
}
template <size_t size>
void MySafeStrncpy(char (&strDest)[size],const char *strSource)
{
MySafeStrncpy(strDest,size,strSource);
}
template <size_t sizeDest,size_t sizeSource>
void MySafeStrncpy(char (&strDest)[sizeDest],
const char (&strSource)[sizeSource])
{
MySafeStrncpy(strDest,sizeDest,strSource,sizeSource);
}
template <size_t sizeSource>
void MySafeStrncpy(char *strDest,size_t maxDestSize,
const char (&strSource)[sizeSource])
{
MySafeStrncpy(strDest,maxDestSize,strSource,sizeSource);
}
使用代码在Visual C++ 2008编译时出现错误:
char threadname[16];
MySafeStrncpy(threadname,"MainThread");
error C2668: 'MySafeStrncpy' : ambiguous call to overloaded function
> could be 'void MySafeStrncpy<16,11>(char (&)[16],const char (&)[11])'
> or 'void MySafeStrncpy<16>(char (&)[16],const char *)'
> while trying to match the argument list '(char [16], const char [11])'
我在这里做错了什么?
在确定调用哪个模板函数时,编译器似乎无法确定字符串文字 "MainThread" 是否应该被视为 const char * 或 const char[11]。
我希望它将字符串文字视为const char[11] 并选择void MySafeStrncpy<16,11>(char (&)[16],const char (&)[11]) 变体,因为这是“最安全的”。
还有两个对答案的限制:1)我无法切换编译器(代码在其他编译器上编译)和 2)公司不允许我使用外部模板库作为解决方案。
【问题讨论】:
-
你会很高兴听到 g++ 编译它:)
-
@themel:感谢您的关注。我在我的问题中澄清了这是 Visual C++ 2008 中的一个问题。
-
仅供参考,当我发现重载(大约在 1997 年)时,我经常使用它并认为它是多么酷/多么聪明。大约 5 年前,我几乎完全停止使用重载 - 是的,我现在有了 print1、print2 等函数。主要原因:当我使用 IDE 搜索我的项目时,我只得到我要查找的内容,无需从长长的名单。
-
@radim:这些功能都彼此相邻,一点也不令人困惑。另外,这段代码显然在某些编译器上编译得很好:-(
标签: c++ arrays templates visual-c++ overloading