On Monday, 14 August 2017 at 13:48:36 UTC, Dominikus Dittes Scherkl wrote:
if I use fixed-type functions, I can do the following:

uint foo(uint n)
{
++n; // modify n - as this function has received a copy of n, this is always possible
   return 42;
}

uint bar(const uint n)
{
   assert(foo(n)==42);
   return 17;
}

void main()
{
   bar(3);
}


But if I try the same with a template parameter, it doesn't work:

import std.traits; // Unqual

uint foo(T)(Unqual!T n) // first try
{
   ++n; // modify should be possible
   return 42;
}

uint foo2(T)(T n) // second try
{
   ++n; // modify fails, as T is const
   return 42;
}

uint bar(T)(const T n)
{
   assert(foo(n)==42u); // cannot deduce arguments - why?!?
assert(foo2(n)==42u); // here it can deduce the arguments, but the function cannot modify n
   return 17;
}

void main()
{
   bar(3);
}

Any ideas what I need to do to make this work?

hi dominikus

you can call functions as func(arg) when compiler can infer the types for your functions but when it's not you'll get an "cannot deduce arguments" error.

when you call bar template function, you won't be able to modify the argument n. ++n will not work and will throw an error at compile time.

    import std.traits : Unqual;
    import std.stdio : writeln;

    uint normalFoo(int n) {
        ++n;
        return n;
    }

    uint constNormalFoo(const int n) {
        ++n; // will raise error
        return n;
    }

    uint templateFoo(T)(Unqual!T n) {
        ++n;
        return n;
    }

    uint constTemplateFoo(T)(const Unqual!T n) {
        ++n; // will raise error
        return n;
    }

    void main() {
        writeln(normalFoo(42));
        // writeln(constNormalFoo(42));
        writeln(templateFoo!int(42));
        // writeln(constTemplateFoo!int(42));

    }

more info is available at:

Reply via email to