www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - "This for <member> needs to be type <class>, not type <otherclass>"

reply Simen Kjaeraas <simen.kjaras gmail.com> writes:
While playing around with templates and alias parameters, I got the die of
trying this:

struct foo(alias T)
{
  typeof(T) opAddAssign(typeof(T) rhs)
  {
    return T += rhs;
  }
}

class bar
{
private:
  int _baz;
public:
  foo!(_baz) baz;
}

When compiling this, I get the message "Error: this for_baz needs to be type
bar not type foo!(_baz)*"

Is there a workaround to this, or even a plan to make such things possible in
the future?

-- Simen
May 02 2008
parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Simen Kjaeraas" <simen.kjaras gmail.com> wrote in message 
news:fvfg2g$1nnp$1 digitalmars.com...
 While playing around with templates and alias parameters, I got the die of 
 trying this:

 struct foo(alias T)
 {
  typeof(T) opAddAssign(typeof(T) rhs)
  {
    return T += rhs;
  }
 }
If you make this a template: template foo(alias T) // rest is the same
 class bar
 {
 private:
  int _baz;
 public:
  foo!(_baz) baz;
And now change this to a mixin: mixin foo!(_baz) baz; It works. Of course, this has the effect of making foo (or rather an instance of foo) no longer a type. But maybe you don't need it to be.
May 02 2008
parent Simen Kjaeraas <simen.kjaras gmail.com> writes:
Jarrett Billingsley Wrote:

 "Simen Kjaeraas" <simen.kjaras gmail.com> wrote in message 
 news:fvfg2g$1nnp$1 digitalmars.com...
 While playing around with templates and alias parameters, I got the die of 
 trying this:

 struct foo(alias T)
 {
  typeof(T) opAddAssign(typeof(T) rhs)
  {
    return T += rhs;
  }
 }
If you make this a template: template foo(alias T) // rest is the same
 class bar
 {
 private:
  int _baz;
 public:
  foo!(_baz) baz;
And now change this to a mixin: mixin foo!(_baz) baz; It works. Of course, this has the effect of making foo (or rather an instance of foo) no longer a type. But maybe you don't need it to be.
Now why didn't I think of that... I have to say the mixin syntax is uglier, but it gets the job done. There are times when I wish I could declare a function, template or whatever to be a mixin type, so any instantiation of it would be a mixin. If that were to be implemented, I wouldn't have the ugly 'mixin' keyword cluttering my code. It would make code cleaner, but mayhaps more hard to read. -- Simen
May 02 2008