c – 用于复制两个字符数组的模板函数
发布时间:2020-12-16 03:37:54 所属栏目:百科 来源:网络整理
导读:我正在尝试替换旧的C宏: // Copy the contents of the character array b into character array a. If the source// array is larger than the destination array,limit the amount of characters copied#define STRCPY(a,b) if(b) strncpy(a,b,sizeof(a) s
我正在尝试替换旧的C宏:
// Copy the contents of the character array b into character array a. If the source // array is larger than the destination array,limit the amount of characters copied #define STRCPY(a,b) if(b) strncpy(a,b,sizeof(a) < sizeof(b) ? sizeof(a) : sizeof(b)) 我希望模板能有所帮助.也许这样的事情,但它不起作用. template <typename T,size_t N,typename TT,size_t M> void scopy(T (dest[N]),const TT (src[M])) { strncpy(dest,src,N < M ? N : M); } int main() { char foo[10] = "abc"; char bar[5] = "xyz"; scopy(foo,bar); } gcc报告不好 编辑:我的伪示例使用了不同于我获得的实际编译器错误的不同大小的数组.现在修复了 error: no matching function for call to ‘scopy(char [5],const char [10])’ 解决方法
您需要引用数组,因为数组不能通过值传递(这也没有意义,因为您实际上想要修改原始数组):
template <typename T,size_t M> void scopy(T (&dest)[N],const TT (&src)[M]) { strncpy(dest,N < M ? N : M); } 您可能还应断言sizeof(T)== 1和sizeof(TT)== 1,因为否则strncpy不会做正确的事情.或者,如果您感觉现代,请更换身体: std::copy_n(src,N < M ? N : M,dst); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |