Determining Whether a Symbol is a Template Function
Asked Answered
H

1

6

I'm trying to come up with a robust way of determining whether a given symbol is a function template. The following:

import std.traits: isSomeFunction;

auto ref identity(T)(auto ref T t) { return t; }

static assert(isSomeFunction!identity);

Will fail as identity is still a template until it is instantiated. Currently I am using a hack that relies on the fact that <template function symbol>.stringof is formatted a certain way:

//ex: f.stringof == identity(T)(auto ref T t)
template isTemplateFunction(alias f)
{
    import std.algorithm: balancedParens, among;

    enum isTemplateFunction = __traits(isTemplate, f) 
        && f.stringof.balancedParens('(', ')') 
        && f.stringof.count('(') == 2 
        && f.stringof.count(')') == 2;
}

//Passes
static assert(isTemplateFunction!identity);

I'd like to know if there's a better way to do this other than hacky stringof parsing.

Heilungkiang answered 9/10, 2015 at 17:16 Comment(1)
stringof might be the best you are going to get since to do further testing you'd have to instantiate the template and there's no guaranteed way to actually do that. (Consider one with an if(false) constraint, it'd be impossible to ever get inside it).Veldaveleda
H
0

It seems there's no better way to do this in D as it is now, so I will stick to parsing .stringof, as dirty a hack as it is.

Heilungkiang answered 13/10, 2015 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.