There is an old C macro that I'm trying to replace:
// 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))
I was hoping templates would help. Maybe something like this, but it doesn't work.
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 reports badness
Edit: My pseudo example used different sized arrays than the actual compiler error I was getting. Fixed now
error: no matching function for call to ‘scopy(char [5], const char [10])’
You need references to arrays, since arrays cannot be passed by value (nor would that make sense, since you actually want to modify the original array):
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);
}
You should probably also assert somewhere that sizeof(T) == 1
and sizeof(TT) == 1
, since otherwise strncpy
isn't going to be doing the right thing. Or, if you feel modern, replace the body with:
std::copy_n(src, N < M ? N : M, dst);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With