www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - templates and scoping

reply Ellery Newcomer <ellery-newcomer utulsa.edu> writes:
this is going to be a bit of a nebulous question, but

if I define a template

template T(string s){
}

where s is an identifier, then is there a good way to branch T's 
behavior based on whether s is declared in the scope in which T gets 
instantiated?
Apr 01 2010
parent reply BCS <none anon.com> writes:
Hello Ellery,

 this is going to be a bit of a nebulous question, but
 
 if I define a template
 
 template T(string s){
 }
 where s is an identifier, then is there a good way to branch T's
 behavior based on whether s is declared in the scope in which T gets
 instantiated?
 

some combination of "is()" "typeof" and "mixin()" should do it. //untested static if( mixin("is("~s~")") ) { ... } -- ... <IXOYE><
Apr 01 2010
parent reply Ellery Newcomer <ellery-newcomer utulsa.edu> writes:
On 04/01/2010 12:38 PM, BCS wrote:
 Hello Ellery,

 this is going to be a bit of a nebulous question, but

 if I define a template

 template T(string s){
 }
 where s is an identifier, then is there a good way to branch T's
 behavior based on whether s is declared in the scope in which T gets
 instantiated?

some combination of "is()" "typeof" and "mixin()" should do it. //untested static if( mixin("is("~s~")") ) { ... }

All right, here's a first try: //// test.d module test; import tok; int a; //1 void main(){ int a; //2 void dummy(){}; mixin T!("a"); } //// tok.d module tok; int a; //3 template T(char[] k){ static if (is(typeof(mixin(k)))){ pragma(msg,"true"); static if(is(typeof(mixin("."~k)))){ pragma(msg,"uh oh"); } const K = true; }else{ pragma(msg,"false"); const K = false; } } The problem I see is it can't distinguish between 1 or 2 and 3
Apr 03 2010
parent BCS <none anon.com> writes:
Hello Ellery,

 The problem I see is it can't distinguish between 1 or 2 and 3
 

OK, lets try a slightly different question: Can code statically branch on what scope some symbol is in? I'd look at __traits but I don't know how to do this off hand. Being in a template mixin and getting passed in as a string just confuse the issue. -- ... <IXOYE><
Apr 03 2010