Al Bundy Al Bundy - 2 months ago 9
C++ Question

Specialized template for safe copy of char [] with boundary check

Due to the fact I am working in the project with a library which uses C API I have to use partial

char []
[even I would love to use only
std::string
].

How ever, in order to avoid problems when copying a too long
char *
variable to a fix-sized
char []
I was trying to catch this problem with a template.

But unfortunately I am stuck with the specialization. In the project we can assume that the destination variable is always of type
char [fixed-value]
AND it must not be
char *
. This is therefore important because there is not really a reliable way to determinate for sure the size of the allocated size of a
char *
.

This is what I tried that far:

#include <stdio.h>

template <typename T>
void copyWithBoundaryCheck( char destination [], char * source, int maximalSize )
{
printf( "Correct parameter\n" );
};

template <typename T>
void copyWithBoundaryCheck( T, char * source, int maximalSize )
{
printf( "Wrong parameter\n" );
};

int main()
{
char * source = (char *) "Source";
char * wrongPtr = (char *) malloc( 20 );
char destination [20];

copyWithBoundaryCheck( wrongPtr, source, 10 );
copyWithBoundaryCheck( destination, source, sizeof(destination) );
}


This is the output:

Wrong parameter <-- output for copyWithBoundaryCheck( wrongPtr, source, 10 );
Wrong parameter <-- output for copyWithBoundaryCheck( destination, source, sizeof(destination) );


For
copyWithBoundaryCheck( destination, source, sizeof(destination) );
I was expecting the output
Correct parameter
but I receive always
Wrong parameter
.

My question:

How has to be implemented the specialization of the template function
copyWithBoundaryCheck
to catch
char [numeric-value]
? According to my example it would mean that
copyWithBoundaryCheck( destination, source, sizeof(destination) );
would display
Correct parameter
.

Answer

You are probably looking for something like this:

template <size_t N>
void copyWithBoundaryCheck(char (&destination)[N])
{
    printf( "Correct parameter of size %zu\n", N );
};

Demo

Comments