Template function for copying two character arrays

There is an old C macro that I am 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 the templates would help. Maybe something like this, but it does not 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 bad

Edit: in my pseudo-example, different sizes of arrays were used than the actual compiler error I was getting. Fixed now

  error: no matching function for call to 'scopy(char [5], const char [10])' 
+6
source share
1 answer

You need references to arrays, since arrays cannot be passed by value (and this does not make sense, since you really want to change 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 argue that sizeof(T) == 1 and sizeof(TT) == 1 , since otherwise strncpy will not do the right thing. Or, if you feel modern, replace the body:

 std::copy_n(src, N < M ? N : M, dst); 
+9
source

All Articles