In the first use of strcpy_s
, the number of elements in the array szTemp
is part of the type of szTemp
(since it is an “array of 512 TCHAR
”), so the compiler knows about it and can complete the template that declares strcpy_s
.
In the second use of strcpy_s
, pszTemp
is a pointer (it is a “pointer to TCHAR
”), not an array, and the number of elements pointed to is not part of the type. In general, a compiler cannot know how many elements are at the place where a pointer points. (In this case, a compiler might deduce it, since the preceding code shows it, but that adds complications to the compiler and the language that are generally regarded to be not worth implementing.)
To do this yourself, declare a template the way strcpy_s
is declared:
template <size_t size> errno_t strcpy_s(
char (&strDestination)[size],
const char *strSource
);
This declares a template based on parameter size
, and the template is for a function whose first parameter has the type “reference to an array of size
elements of char
”. When the compiler sees the use of strcpy_s
with a first argument that is an array of 512 elements of char, it is able to match this argument to the parameter in the template, and it deduces that size
is 512.
Somewhere else, you will have a definition of the template (not just a declaration). That definition can use the template parameter size
in its code. When the compiler sees the use of strcpy_s
, it will instantiate the template definition in a specialization where size
is 512.
This only works in C++, not C, because C does not have templates.