C++ 复制两个字符数组的模板函数

C++ 复制两个字符数组的模板函数,c++,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) ?

我正在尝试替换一个旧的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))
您需要对数组的引用,因为数组不能通过值传递(这也没有意义,因为您实际上想要修改原始数组):


当然,使用像
char dest[100]
这样的参数也可以。问题是模板参数推断规则指定参数类型在推断之前衰减,除非参数是引用。@BrianBi:我不太确定您指的是什么。声明
void f(char*)
void f(char[])
void f(char[10])
都是相同的。方括号在函数声明符中有特殊含义。没有“衰变”。(衰减发生在调用表达式中。)您说过需要引用数组的原因是数组不能按值传递。但这似乎并不能解释任何事情,因为没有引用的声明器仍然不会按值传递数组。您需要引用的实际原因是,正如您所说的,防止“调用表达式”中的衰减。(如果发生衰变,则无法推断范围。)该错误真的来自该代码吗?
7
从哪里来?顺便说一句,接受
T
但在假设它是
char
的情况下使用它,这本身就是错误的。请接受关于如何验证该类型是char的建议。只需让编译器为您这样做:
模板(char(&dst)[N],char const(&src)[M])
?或者,放弃假设,在内部使用
copy\n
copy
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);
}
 error: no matching function for call to ‘scopy(char [5], const char [10])’
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);
}
std::copy_n(src, N < M ? N : M, dst);