[cfe-dev] How to perform template substitution in the clang library

John McCall rjmccall at apple.com
Tue Nov 27 15:27:45 PST 2012


On Nov 26, 2012, at 2:55 PM, stewart mackenzie <setori88 at gmail.com> wrote:
> I have it on authority that the timing of my previous questions were dismal! So I'll start the question on a happy Thanksgiving note.
> 
> We have a C++ source file like this:
> 
>     template <int n>
>     struct N {};
> 
>     struct B {
>         template <typename M>
>         using A = typename std::conditional<std::is_same<M, N<4>>::value,
>                                             int*, void*>::type;
>     };
> 
>     template <typename T, T value>
>     struct F : B {};
> 
>     template <>
>     struct F<decltype(&fopen), &fopen> : B {
>         template <typename M>
>         using A = double*;
>     };
> 
>     template <>
>     struct F<decltype(&fclose), &fclose> : B {
>         template <typename M>
>         using A = typename std::conditional<std::is_same<M, N<16>>::value,
>                                             void*, char**>::type;
>     };
> 
>     // More specialization of 'F' follows.
> 
> It is easy to find the ClassTemplateDecls (http://clang.llvm.org/doxygen/classclang_1_1ClassTemplateDecl.html) of `N` and `F`, and the
> QualType (http://clang.llvm.org/doxygen/classclang_1_1QualType.html)
> and FunctionDecl (http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html)
> of the function pointers `&fopen`, `&fclose`, etc. But the problem is
> how to substitute these arguments into N, F and F::A without modifying
> the source code.
> 
> The question is:
> 
> * How do I evaluate `F<decltype(&fprintf), &fprintf>::A<N<4>>` and
> know that it is an `int*`?
> * How do I evaluate `F<decltype(&fopen), &fopen>::A<N<7>>` and know
> that it is a `double*`?
> * and so on...
> 

Template instantiation requires an active Sema object.  The interface to
Sema isn't stable, and it's not tremendously well-documented, but
basically you just want to imitiate the series of calls that the parser would
make in order to build up the type expression that you need.

John.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20121127/f2601f36/attachment.html>


More information about the cfe-dev mailing list