title: Creating template specializations via a macro
body: <p>I'm trying to create a helper method <code>createTypedArray</code> that "knows" how many bytes per element to allocate. That is, <code>createTypedArray&lt;Float32Array&gt;(size)</code> and not <code>createTypedArray&lt;Float32Array, 4&gt;(size)</code>.</p>
  
  <p>This is the best approach I've come up with. Is there a better approach? There's a dummy primary template that I don't love, at least.</p>
  
  <pre><code>#define TYPED_ARRAY_P(T, bytesPerElement)                                            \
    template &lt;&gt;                                                                        \
    Local&lt;T&gt; createTypedArray&lt;T&gt;(size_t size) {                                        \
      size_t byteLength = size * bytesPerElement;                                      \
      Local&lt;ArrayBuffer&gt; buffer = ArrayBuffer::New(Isolate::GetCurrent(), byteLength); \
      Local&lt;T&gt; result = T::New(buffer, 0, size);                                       \
      return result;                                                                   \
    }
  
  // Dummy
  template &lt;typename T&gt;
  Local&lt;T&gt; createTypedArray(size_t s) {
    return void;
  }
  
  TYPED_ARRAY_P(Uint8Array, 1);
  TYPED_ARRAY_P(Uint16Array, 2);
  TYPED_ARRAY_P(Uint32Array, 4);
  
  #undef TYPED_ARRAY_P
  </code></pre>