Skip to content

Instantly share code, notes, and snippets.

@dwilliamson
Last active August 29, 2015 14:05
Show Gist options
  • Save dwilliamson/b8849451ee430c5d2194 to your computer and use it in GitHub Desktop.
Save dwilliamson/b8849451ee430c5d2194 to your computer and use it in GitHub Desktop.
Generics stored and parsed in C-style comments, generating code directly after them whenever the comments change.
//
// Pre-processor scans your C/header file for the '/*$gen:' signature
// It consumes everything inside the C-style comment and generates a unique hash
// This hash is used to determine if the contents of the comment have changed since it last looked
// The hash is stored after the '/*$gen:' signature
//
/*$gen:0x1AF673C3
// This is your generic implementation with (T) the generic type
// Token-pasting is done by default if there is no white-space after (T)
(T) dot3((T)3 a, (T)3 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
// These are the function instantiations you ask it to generate
dotf = dot3(float)
dotd = dot3(double)
doti = dot3(int)
*/
// The pre-processor generates the following code in your C file whenever the signature hash changes
// $inst-begin:0x1AF673C3
float dotf(float3 a, float3 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
double dotd(double3 a, double3 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
int doti(int3 a, int3 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
// $inst-end
@dwilliamson
Copy link
Author

Benefits:

  • Domain-specific generic language that's friendlier than the C pre-processor.
  • Allows 3rd parties to use your code without requiring the generics pre-processor.
  • Visible code foot-print for all explicitly generated instantiations (unlike C++ templates).
  • Each implementation can be stepped-through in a debugger.

Drawbacks:

  • Requires pre-process on your code. Should be fast though, given it can exempt large swathes of code with the gen signature.
  • Obviously not as good as a decent generics implementation for your language.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment