www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Template parameter shadowing

reply klickverbot <see klickverbot.at> writes:
In short, should the following be allowed?

---
class Class(T) {
   string foo(T)(T arg) {
     return T.stringof;
   }

   string bar() {
     return T.stringof;
   }
}

unittest {
   auto c = new Class!int;
   assert(c.foo("asdf") == "string");
   assert(c.bar() == "int");
}
---

Note that the T type parameter to the template function shadows the one 
from the template class, which might be a source of confusion since T 
refers to class template parameter in other member functions.
Sep 22 2010
next sibling parent F. Almeida <francisco.m.almeida gmail.com> writes:
== Quote from klickverbot (see klickverbot.at)'s article
 In short, should the following be allowed?
 ---
 class Class(T) {
    string foo(T)(T arg) {
      return T.stringof;
    }
    string bar() {
      return T.stringof;
    }
 }
 unittest {
    auto c = new Class!int;
    assert(c.foo("asdf") == "string");
    assert(c.bar() == "int");
 }
 ---
 Note that the T type parameter to the template function shadows

 from the template class, which might be a source of confusion

 refers to class template parameter in other member functions.

It should not be allowed. The compiler should forbid using the same symbol for distinct template parameters. I'm surprised if this even compiles.
Sep 22 2010
prev sibling parent "Simen kjaeraas" <simen.kjaras gmail.com> writes:
klickverbot <see klickverbot.at> wrote:

 In short, should the following be allowed?

 ---
 class Class(T) {
    string foo(T)(T arg) {
      return T.stringof;
    }

    string bar() {
      return T.stringof;
    }
 }

 unittest {
    auto c = new Class!int;
    assert(c.foo("asdf") == "string");
    assert(c.bar() == "int");
 }
 ---

 Note that the T type parameter to the template function shadows the one  
 from the template class, which might be a source of confusion since T  
 refers to class template parameter in other member functions.

I believe this is acceptable in the current spec, and as such would be an enhancement request (local symbols are allowed to shadow global). That said, I believe it is worthy of inclusion, as one much more rarely wants to shadow template parameters. -- Simen
Sep 22 2010