Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template function to copy two character arrays

Tags:

c++

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])’
like image 433
LeviX Avatar asked Mar 04 '14 20:03

LeviX


1 Answers

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);
like image 83
Kerrek SB Avatar answered Sep 30 '22 13:09

Kerrek SB