www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Public variables inside interfaces

reply =?UTF-8?B?TWFyaXVzeiBHbGl3acWEc2tp?= <alienballance gmail.com> writes:
I like the possibility of abandoning () in function calls in D, so we 
can firstly make attribute public and then if implementation changes, 
smoothly change it into function:

call:
<code>
auto a = new A();
writeln("Size is " +a.size);
auto b = new B();
writeln("Size is " +b.size);

class A {
     public int size = 0;
}

class B {
     public int size() { return 0; }
}
</code>

Although, if I'd like to make interface Sizeable, it's impossible to 
treat attribute and method equally:
<code>
interface Sizeable {
/*
     int size;   // Error: variable Sizeable.size field not allowed in 
interface
     int size(); //
*/
class A : Sizeable {
     public int size = 0; // Error: Does not implements int size()
}

class B : Sizeable {
     public int size() { return 0; }
}
</code>

Is it possible to make it work?

Best regards,
Mariusz Gliwiński
Apr 30 2011
next sibling parent Peter Alexander <peter.alexander.au gmail.com> writes:
On 30/04/11 1:22 PM, Mariusz Gliwiński wrote:
 I like the possibility of abandoning () in function calls in D, so we
 can firstly make attribute public and then if implementation changes,
 smoothly change it into function:
 <snip>

 Although, if I'd like to make interface Sizeable, it's impossible to
 treat attribute and method equally:
 <snip>

 Is it possible to make it work?

 Best regards,
 Mariusz Gliwiński
No, interface functions require entries in the v-table, so the implementing class needs to have a function. You could certainly get around it using mixins and metaprogramming, but there's no need for that level of complexity when all you need to do is implement a function that returns a member variable.
Apr 30 2011
prev sibling parent Olivier Pisano <olivier.pisano laposte.net> writes:
Hi,

You can "disguise" method calls into variables by using the  property tag.

interface Sizeable
{
     // Getter
      property int size();

     // Setter
      property int size(int s);
}

class A : Sizeable
{
     int m_size;

public:
     this()
     {

     }
      property int size() { return m_size; }
      property int size(int s) {return m_size = s; }
}

static void main(string[] args)
{
     A a = new A();
     a.size = 20; // calls a.size(int);

     int i = a.size + 10; // calls a.size()
}


Cheers,

Olivier.
Apr 30 2011