www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Type name shadowing

reply "ixid" <adamsibson hotmail.com> writes:
T shadow(T = int)(T a) {
	alias T = string;
	T b = "hi";
	T c = 1; // Error

	writeln(typeof(a).stringof); // int
	writeln(typeof(b).stringof); // string

	return a;
}


Are there uses for this shadowing of type names? It seems a 
little dangerous, for example ulong T could be shadowed by uint 
T. Is there a reason to allow it?
Oct 25 2014
parent "H. S. Teoh via Digitalmars-d-learn" <digitalmars-d-learn puremagic.com> writes:
On Sat, Oct 25, 2014 at 12:28:39PM +0000, ixid via Digitalmars-d-learn wrote:
 T shadow(T = int)(T a) {
 	alias T = string;
 	T b = "hi";
 	T c = 1; // Error
 
 	writeln(typeof(a).stringof); // int
 	writeln(typeof(b).stringof); // string
 
 	return a;
 }
 
 
 Are there uses for this shadowing of type names? It seems a little
 dangerous, for example ulong T could be shadowed by uint T. Is there a
 reason to allow it?
The problem gets worse than that. For example: ----external_library.d---- module external_library; alias T = string; ----main.d---- module main; void func(T = int)(T i) { import external_library; pragma(msg, T.stringof); // prints 'string' } void main() { func(1); } Imagine that the 'alias T' was not present in an earlier version of the library, but now has been added by the library author. Suddenly, user code breaks without warning. T -- Error: Keyboard not attached. Press F1 to continue. -- Yoon Ha Lee, CONLANG
Oct 25 2014