我有以下代码用于“安全”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,sizeSource); } template <size_t sizeSource> void MySafestrncpy(char *strDest,maxDestSize,sizeSource); }
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])变体,因为那是最安全的”.