Why are interfaces so restrictive?

BCS BCS_member at pathlink.com
Fri Mar 17 17:01:05 PST 2006


Why can only classes implement an interface?

     If I understand correctly, an instance of an interface is a context pointer 
along with a pointer to a table of function pointers. When a method of an 
interface is called, the function pointer is called with the context pointer as 
the first argument. In effect, it is a delegate using a table of function 
pointers rather than just one.
     Calling a method of a class isn't the only way to get a delegate, they can 
be made from a struct or even a local function, so why not let a struct 
implement an interface or even let a function define an interface literal.

For example:
-------------------

interface Database
{
	Item SerchForItem(char[]);
	bool AddItem(char[], Item);
	bool RemoveItem(char[]);
}

void DatabaseUI(Database);

void Foo()
{
	Item[char[]] bar;

	Database db = interface:Database
	{
		Item SerchForItem(char[] n)
		{
			if(n in bar)
				return bar[n];
			throw new Error("blah!");
		}

		bool AddItem(char[] n, Item i)
		{
			if(n in bar)
				throw new Error("blah!");
			bar[n] = i;
			return true;
		}

		bool RemoveItem(char[] n)
		{
			if(n in bar)
			{
				bar.remove(n);
				return true;
			}
			throw new Error("blah!");
		}
	}

	DatabaseUI(db);

	...
}


---------------------
p.s. Maby there should be a NG for post 1.0 stuff.



More information about the Digitalmars-d mailing list