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

C对重载函数的不明确调用,第1张

概述我有以下代码用于“安全”strncpy() – 基本上它的包装器自动为字符串缓冲区采用固定的数组大小,因此你不必做额外的工作来传递它们(这样的便利是更安全的,因为你赢了不小心为固定数组缓冲区输入了错误的大小. inline void MySafeStrncpy(char *strDest,size_t maxsize,const char *strSource){ if(maxsize) 我有以下代码用于“安全”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对重载函数的不明确调用全部内容,希望文章能够帮你解决C对重载函数的不明确调用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1225671.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存