0

I came across the template version _snwprintf_s

from MSDN:

template <size_t size>
int _snwprintf_s(
   wchar_t (&buffer)[size],
   size_t count,
   const wchar_t *format [,
   argument] ... 
); // C++ only

I understand how to use it, and I'm familiar with c++ templates and the possibility to use templates with an integer.

What is the type of wchar_t (&buffer)[size]? Is it a reference to a wchar_t, if so then what the [size] mean? what is this called?

I'm guessing the compiler infers the size somehow but this is the first time I've come across such syntax and would appreciate an explanation as I haven't found anything on it by myself (probably since I don't know what to search for).

Also, If you can explain how this works behind the scene, that'd be great.

EDIT:

I'm more interested at how this works compiler-wise, less about the type that is passed, which is as mentioned explained here

Thanks

Community
  • 1
  • 1
ZivS
  • 2,094
  • 2
  • 27
  • 48

2 Answers2

3

wchar_t (&buffer)[size] is a reference to array, just as you would write in plain C wchar_t (*buffer)[size] which is a pointer to the array.

ypu can think of a reference as "constant - auto-dereferencing - pointers" and in 99% of the times they are implemented as such.

the point is that C++ compiler can, on compile time only, deduce the type of the arguments and call the right template function.

thus, L"hi" would be deduce as wchar_t[3] and call _snwprintf_s<3>.

this is of course not applicable for something like wchar_t t* = malloc(3*sizeof(wchar_t));, since it's allcoated on run time, and the type of t is wchar_t*

David Haim
  • 25,446
  • 3
  • 44
  • 78
2

buffer is a reference to an object of type wchar_t[size]: that is, a reference to an array of size size of wchar_t.

This is very similar to making the parameter wchar_t buffer[], but there are some advantages: e.g. it lets you do the the template argument deduction here, and I've also seen optimizers perform better in some situations when arrays are passed in this manner.

  • It also isn't a pointer to `wchar_t`, unlike `wchar_t buffer[]`. So it can't bind to such a pointer. – juanchopanza Sep 09 '15 at 11:32
  • 1
    The answer was reading fine, and I was about to upvote it, until I read this *"This is **very similar** to making the parameter wchar_t buffer[]"*. – Nawaz Sep 09 '15 at 11:34