10
votes

Is there a compiler or standalone preprocessor which takes C++ files and runs a template expansion pass, generating new C++ code with expanded template instantiations?

I remember such a tool in the mid-90s when templates were still new and experimental, and the preprocessor was a way to do template programming with compilers without native template support.

This is a lot more complicated than a macro-processing step since it would likely require parsing and tokenizing the code to understand the contexts.

My hope is to use such a tool when writing OpenCL code. OpenCL is C++, but does not support templates. I'm hoping I can write templates, even simple ones like with integer or bool only arguments, and have some tool pre-parse the file and go through and find the use of the templates and expand the invocations and give me new C++ code that the OpenCL compiler can understand.

Even a very limited tool could be useful, it does not need to support every template quirk, nor even support multiple modules or anything.

The alternative: #define macros everywhere.. uglier, unsafe, less efficient, and less versatile.

2
OpenCL's language is based on C99 syntax, not C++ according to the page you linked. - Evan Teran
AMD do some extension to openCL, you could develop template codes if you aim for the AMD devices only.It is a pain that we could not use template to develop our algorithms. - StereoMatching

2 Answers

10
votes

Comeau C++ can "compile" C++ to C. This would seem to be close to your goal, as OpenCL does not support C++ – it's much closer to C.

0
votes

There is no such tool - templates are part of the language, not some pre-processor pass - they are processed by the compiler, just like other code.