用于复制两个字符数组的模板函数

Lev*_*viX 6 c++

我正在尝试替换旧的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))
Run Code Online (Sandbox Code Playgroud)

我希望模板能有所帮助.也许这样的事情,但它不起作用.

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);
}
Run Code Online (Sandbox Code Playgroud)

gcc报告不好

编辑:我的伪示例使用了不同于我获得的实际编译器错误的不同大小的数组.现在修复了

 error: no matching function for call to ‘scopy(char [5], const char [10])’
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 9

您需要引用数组,因为数组不能通过值传递(这也没有意义,因为您实际上想要修改原始数组):

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);
}
Run Code Online (Sandbox Code Playgroud)

你应该还断言的地方,sizeof(T) == 1并且sizeof(TT) == 1,否则strncpy是不会做正确的事情.或者,如果您感觉现代,请更换身体:

std::copy_n(src, N < M ? N : M, dst);
Run Code Online (Sandbox Code Playgroud)