C对重载函数的不明确调用

我有以下代码用于“安全”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);
}

在编译时使用代码导致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)公司不允许我使用外部模板库来解决问题.

解决方法

根据13.3.3.1.1,数组到指针的转换具有完全匹配
rank,所以这个函数调用在标准规范中可能不明确.
如果允许您更改定义:

template <size_t size>
void MySafestrncpy(char (&strDest)[size],const char *strSource)

至:

template <size_t size,class T>
void MySafestrncpy(char (&strDest)[size],T strSource)

here,那么这可能就是最简单的解决方法.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...