微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,那么这可能就是最简单的解决方法.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐