Forward declarations of template specilizations.

Ryan Bloomfield _sir_maniacREMOVE_ME at yahoo.com
Fri Nov 14 12:30:38 PST 2008


I have an interesting issue, that makes me curious on how D handles it.

consider the following:
======================
module List;

template NodeTraits(NodeType)
{
	static NodeType getNext(NodeType v) { return v.next; }
}

class List(NodeType, Traits=NodeTraits!(NodeType))
{
	private NodeType head;

	
	NodeType next() { return Traits.getNext(head); }
}

======================
module main;

class Node {
	Node myNext;
}

template NodeTraits(NodeType : C)
{
	static NodeType getNext(NodeType v) { return v.myNext; }
}

main()
{
    	alias List!(Node) L;
	L l = new L();
	C next = l.next(); // error:  no property 'next' for type 'main.Node'
}
==============================================


  Templates are evaluated in the scope they are defined, which makes sense, but when should the compiler check those definitions?  It makes sense that given 2 modules, one module shouldn't be able to change the behavior of another module, having said that, c++ does allow this, and it proves very useful in customizing the behavior of library classes.

  I noticed that if I change it to the following it works correctly(Traits argument becomes an alias, and is passed in main):
======================
module List;

template NodeTraits(NodeType)
{
	static NodeType getNext(NodeType v) { return v.next; }
}

class List(NodeType, alias Traits)
{
	private NodeType head;

	
	NodeType next() { return Traits.getNext(head); }
}

======================
module main;

class Node {
	Node myNext;
}

template NodeTraits(NodeType : Node)
{
	static NodeType getNext(NodeType v) { return v.myNext; }
}

main()
{
       alias NodeTraits!(Node) Traits;  // a template's alias arguments only take a single identifier
    	alias List!(Node, Traits) L;
	L l = new L();
	C next = l.next(); // Successfully accesses l.myNext
}
==============================================

Does the evaluation of a template have to know only the scope it was instantiated in?  No forward declaration(of a module that imports it)?



More information about the Digitalmars-d mailing list