On Wednesday, 27 March 2013 at 15:34:20 UTC, Vidar Wahlberg wrote:

- While the "auto"-keyword often is great, it can lead to difficulties, especially when used as the return type of a function, such as "auto foo() { return bar; }". Sometimes you may wish to store the result of a function/method call as a global variable/class member, but when the function/method returns "auto" it's not apparent what the data type may be. While you may be able to find out what "bar" is by digging in the source code, it can still be difficult to find. One example is to save the result of "std.regex.match()" as a member in a class. For me the solution was to "import std.traits", create a function "auto matchText(string text) { return match(text, myRegex); }" and define the class member as "ReturnType!matchText matchResult;" (do also note that function & member must come in the right order for this to compile). This was all but obvious to a novice D coder as myself, the solution was suggested to me in the IRC channel.

This is actually nothing to do with auto. It's endemic to all templated returns from functions and the same is true in c++ (I don't know enough about java generics to comment).

A solution to your particular problem

class A(type_of_myRegex) {
    alias ReturnType!(match!(string, type_of_myRegex)) RegexR;
    RegexR r;
    void foo(string text, type_of_myRegex myRegex) {
        r = match(text, myRegex);
    }
}

of course, if you only ever use one Regex type then of course you could do without the templating in the class and hard-code it in.

Reply via email to