加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:57:45 所属栏目:百科 来源:网络整理
导读:我有以下代码用于“安全”strncpy() – 基本上它的包装器自动为字符串缓冲区采用固定的数组大小,因此你不必做额外的工作来传递它们(这样的便利是更安全的,因为你赢了不小心为固定数组缓冲区输入了错误的大小. inline void MySafeStrncpy(char *strDest,size_
我有以下代码用于“安全”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,那么这可能就是最简单的解决方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读