Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there scala-like mixins for C++?

Tags:

Scala Mixins

like image 273
Łukasz Lew Avatar asked Feb 03 '09 01:02

Łukasz Lew


People also ask

What is a mixin in scala?

In scala, trait mixins means you can extend any number of traits with a class or abstract class. You can extend only traits or combination of traits and class or traits and abstract class. It is necessary to maintain order of mixins otherwise compiler throws an error.

What is a scala trait?

In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.


2 Answers

No, but it can be faked to varying degrees with templates:

template<typename AbsIterator> 
class RichIterator : public AbsIterator {
public:
   template<typename FuncType>
   void foreach(FuncType f) { while( hasNext() ) f( next() ); }
};

class StringIterator {
  std::string m_s;
  int i;
public:
  typedef char T;
  StringIterator() : m_s(), i(0) {} // Unfortunately need this, or 
                                    // else RichIterator
                                    // gets way more complicated
  StringIterator(const std::string &s) : m_s(s), i(0) {}
  void swap(StringIterator& other) {
     m_s.swap(other.m_s);
     std::swap(i, other.i);
  }
  void reset_str(const std::string& s) {
     StringIterator(s).swap(*this);
  }
  bool hasNext() { return i < m_s.length(); }
  char next() { return m_s[i++]; }
};

template<typename Outputable>
void println(const Outputable& o) {
   std::cout << o << std::endl;
}

int main(int argc, char **argv) {
  typedef RichIterator<StringIterator> Iter;
  Iter iter;
  iter.reset_str(argv[1]);
  iter.foreach(&println<Iter::T>);
}

To be totally honest, I've haven't tested this by compiling it, but you should get the idea.

like image 189
Logan Capaldo Avatar answered Sep 18 '22 15:09

Logan Capaldo


Some aspects of Scala mixins can be satisfied using multiple (virtual) inheritance. Unfortunately, this often introduces more problems than it solves. Also, you can't mix and match superclasses on the fly a la:

val me = new Human with Coder with Musician

If you really, really want true mixins, you almost have to go with something like the template solution proposed in the answer by @Logan Capaldo.

like image 21
Daniel Spiewak Avatar answered Sep 19 '22 15:09

Daniel Spiewak