digitalmars.D.learn - Is it possible to set function attributes conditionally?
- wjoe (38/38) Jun 04 2021 Hi,
- Adam D. Ruppe (5/9) Jun 04 2021 If they are templates, just don't specify attributes and the
- wjoe (4/13) Jun 04 2021 That's good to know. Thanks :)
Hi, Consider Allocators, e.g.: ```d struct Mallocator { enum usesGC = false; /// implement alloc, free, etc. nogc } struct GCAllocator { enum usesGC = true; /// implement alloc, free, etc. via the GC } ``` Now I want to have the function attributes set depending on the allocator implementation ```d template AutoGC(ALLOCATOR) if (isAllocator!ALLOCATOR) { static if (!ALLOCATOR.usesGC) AutoGC = pragma(attrib, nogc); else AutoGC = pragma(attrib, none); } AutoGC!ALLOCATOR void fun(ALLOCATOR)() if(isAllocator!ALLOCATOR) { void* p = ALLOCATOR.alloc(1024); // do something with p ALLOCATOR.free(p); } ``` So fun!Mallocator would be nogc and fun!GCAllocator wouldn't be nogc. This is a contrived example. In reality I would use this with custom array, hash map and other container implementations so I could use them in nogc territory by just switching out the allocator. Is it possible to do something like this ?
Jun 04 2021
On Friday, 4 June 2021 at 11:33:32 UTC, wjoe wrote:This is a contrived example. In reality I would use this with custom array, hash map and other container implementations so I could use them in nogc territory by just switching out the allocator.If they are templates, just don't specify attributes and the compiler will infer them for you. If they are not templates, you have to do a separate copy under version or static if.
Jun 04 2021
On Friday, 4 June 2021 at 11:36:09 UTC, Adam D. Ruppe wrote:On Friday, 4 June 2021 at 11:33:32 UTC, wjoe wrote:That's good to know. Thanks :) A separate copy is exactly what I wanted to avoid but since they are templates it's np.This is a contrived example. In reality I would use this with custom array, hash map and other container implementations so I could use them in nogc territory by just switching out the allocator.If they are templates, just don't specify attributes and the compiler will infer them for you. If they are not templates, you have to do a separate copy under version or static if.
Jun 04 2021