Ivan Čukić

Even more curry for C++11

After my initial post about currying in C++, I was wondering whether it is possible to make a universal curry transformation that will be applicable to any functor.

Fortunately, like most weird things, in C++ the answer to this question is yes.

Here, we’ll create a curry object from a lambda function:

  auto log = make_curry(
      [] (int type, int subtype, const std::string & message)
      {
          std::cerr
              << type << " / " << subtype
              << "\t" << message << std::endl;
      }
  );

And use it in all the different ways:

  int main(int argc, const char *argv[])
  {
      auto message = log(1);
      auto error = log(0, 0);

      // Only one argument already given
      message(0, "Normal message");
      message(1, "Important message");

      // We have two arguments already given
      error("No error, just kidding");

      // Or, we can call directly
      log(1, 1, "Arguments: 3 - 0")();
      log(1, 1)("Arguments: 2 - 1");
      log(1)(2, "Arguments: 1 - 2");
      log()(2, 2, "Arguments: 0 - 3");

      return 0;
  }

It allows only to split the function arguments into two sets. I might make it a bit more powerful at some point. I’m a bit sleepy now.

Anyone interested in the code?

Curry all over the C++11

Currying is all-present in functional programming. And we are not really using it.

What is currying? It is a technique of transforming a function that takes multiple arguments in such a way that it can be called as a chain of functions, each with a single argument.

For example, lets look at a simpler version of fprintf function that looks something like this:

  print: (stream, message) -> do something

  // Invoked like this:
  print(cout, "Hello")

If we use the method often with specific streams (like cout, cerr and a log file), we can define it in a different manner, so that we could easily make additional versions specific to those streams. And, we don’t need to impose our opinions of what a user wants by providing a set of convenience functions ourselves (ok, qDebug() is something that everybody wants, but you get the point).

  print: stream -> function called print_to
  print_to: message -> do something

  // It would be invoked like this:
  // (note that the print_to function doesn't
  // really need to be named)
  print(cout)("Hello")

  // or
  log = print(logging_stream)
  err = print(cerr)

  log("Hello")
  err("Error world")

So, this seems totally unneeded, right? It can be quite useful when working with generic code (for example STL algorithms). The following example demonstrates vector partitioning for different predicates.

  #include <string>
  #include <iostream>
  #include <algorithm>
  #include <iterator>

  auto less_than = [] (int i) {
      return [i] (int j) {
          return j < i;
      };
  };

  template <typename B, typename M, typename E>
  inline void write_partitions(B b, M m, E e)
  {
      std::copy(b, m, std::ostream_iterator<int>(std::cout, " "));
      std::cout << "  |  ";

      std::copy(m, e, std::ostream_iterator<int>(std::cout, " "));
  }

  int main(int argc, const char *argv[])
  {
      std::vector<int> ns { 1, -2, 3, -4, 5, -6, 7, -8, 9, -10 };

      // Original vector
      std::copy(ns.begin(), ns.end(),
              std::ostream_iterator<int>(std::cout, " "));
      std::cout << " - Original vector" << std::endl;

      // Partitions for numbers ranging from 0 to 9
      for (int i = 0; i < 10; i++) {
          auto p = std::partition(ns.begin(), ns.end(), less_than(i));

          write_partitions(
              ns.begin(), 
              p,
              ns.end());
          std::cout << " - Predicate: _ < " << i << std::endl;
      }

      return 0;
  }

This is the output it generates:

  -10 -2 -8 -4 -6   |  5 7 3 9 1  - Predicate: _ < 0
  -10 -2 -8 -4 -6   |  5 7 3 9 1  - Predicate: _ < 1
  -10 -2 -8 -4 -6 1   |  7 3 9 5  - Predicate: _ < 2
  -10 -2 -8 -4 -6 1   |  7 3 9 5  - Predicate: _ < 3
  -10 -2 -8 -4 -6 1 3   |  7 9 5  - Predicate: _ < 4
  -10 -2 -8 -4 -6 1 3   |  7 9 5  - Predicate: _ < 5
  -10 -2 -8 -4 -6 1 3 5   |  9 7  - Predicate: _ < 6
  -10 -2 -8 -4 -6 1 3 5   |  9 7  - Predicate: _ < 7
  -10 -2 -8 -4 -6 1 3 5 7   |  9  - Predicate: _ < 8
  -10 -2 -8 -4 -6 1 3 5 7   |  9  - Predicate: _ < 9

Switching the Plasma shells

For Plasma 2, we are aiming to have one plasma to rule them all, but not in the way the others are doing it. We still believe that different form factors need different UIs (I refuse to use UX instead of UI, so sue me :) ). We just want the same application to be able to load the fitting interfaces for the desktop, netbook or tablets. And we want it to be able to dynamically switch between those.

The dynamic switching part I’m working on is almost finished. Namely, everything is prepared for the last step – integrating the new system with the current shells.

Each shell needs the following components:

  • A simple and lightweight loader object
  • And an actual shell implementation that can be done as a C++ plugin or a pure QML thing to make it easier for the common people to create the custom ones.

How does it work?

Note: To avoid confusion, from now on when I write Plasma, I mean the plasma-shell executable that loads the actual shells.

Plasma first gets all the loaders. Loaders need to have two properties defined:

  • ‘willing’ which tells whether it wants to be loaded for the current environment (for example, Plasma Active shell would say ‘yes’ when we have a touch-screen);
  • and ‘priority’ which will allow Plasma to choose between multiple willing shells (for example, an alternative desktop shell that the user installed).

None of these are hard-coded, so a loader can change its mind and, for example, the Desktop shell can set its priority to be as high as possible if we have more than one screen while having a lower one compared to the Active otherwise.

When a suitable shell is found, the loader is requested to create it.

When the environment changes, and the ‘willing’-ness of a loader has been changed, Plasma checks whether it should load a new shell or stick to the old one.

System upgrade

I’ve had an unfortunate situation this week – my system went bust. I’ve been forced to use my netbook for a few days which was rather painful. Fortunately, now it is all over, I’m enjoying a no-swap-ever-needed-8-cpu-core system. Enjoining… if you disregard a very noisy cpu cooler which will need changing.

Introspection in C++, testing whether a class has a specific method

It is sometimes useful to be able to tell whether a class that the user passes as the template parameter has a specific method, or a specific nested type. (the later is quite heavily used for testing the iterator types in STL).

I’ll demonstrate how you can achieve making a universal immutable std::for_each equivalent for associative containers of STL and Qt. It will receive a collection instead of a pair of iterators to make it a bit more pleasant to use. Like this:

template < typename Container, typename Function >
Function for_each_assoc(const Container & c, Function f)

The problem when creating a function like this is that Qt collection classes, although pretending to support STL API sometimes fail miserably. And this is my /favourite/ case.

In STL, you have cbegin() and cend() methods while in Qt those are called constBegin() and constEnd(). The next issue is that iterating the STL associative containers gives you pairs (std::pair) of keys and values, while in Qt you will be getting an object with methods key() and value(). So, we will have to handle them in a different manner.

namespace details {

// Defining two separate methods for STL and Qt classes.

// The code is using the SFINAE (Substitution Failure Is
// Not An Error) rule.

// The compiler will try to match the nullptr we passed
// to the function against the type of the third argument.
// If it doesn't succeed, it will not report an error,
// it will just try to find the next match.

// This method will be invoked if the container
// has a method named constBegin

template <typename Container, typename Function>
Function _for_each_assoc_helper_container(const Container & c, Function f,
        decltype(&Container::constBegin) * )
{
    return qt_for_each_assoc(c.constBegin(), c.constEnd(), f);
}

// This method will be invoked if the container
// has a method named cbegin

template <typename Container, typename Function>
Function _for_each_assoc_helper_container(const Container & c, Function f,
        decltype(&Container::cbegin) * )
{
    return stl_for_each_assoc(c.cbegin(), c.cend(), f);
}

} // namespace details


// The function receives an associative container c and a functor f.
// It will iterate through the container and call f(key, value)
// for every item in it

template <typename Container, typename Function>
Function for_each_assoc(const Container & c, Function f)
{
    return details::_for_each_assoc_helper_container
        <Container, Function>(c, f, nullptr);
}

Now, we just need to add the functions that do the actual work to the details namespace, and we are set to use our new fun generic algorithm.

template 
Function qt_for_each_assoc(Iterator start, Iterator end, Function f)
{
    for ( ; start != end; ++ start ) f(start.key(), start.value());
    return f;
}

template 
Function stl_for_each_assoc(Iterator start, Iterator end, Function f)
{
    for ( ; start != end; ++ start ) f(start->first, start->second);
    return f;
}

For the actual code, you can check out kde:kactivities/src/utils/for_each_assoc.h

String concatenation in Qt5/KF5 (contd.)

There were quite a few comments on my last post. I’d like to clear up a few (imo) misconceptions there.

What I wrote in the last post is not enabled by the default in Qt. So, you should not have any problems during development while using auto with Qt5 (btw, it has almost the same behaviour in Qt4).

From my POV, it is not a bug, but rather an expected behaviour. I only tested the code *after* writing the blog post – already knowing and expecting the result I got. *If* you explicitly enable the optimization, it is expected that you know what you are doing.

The lazy evaluation here is a new feature that auto provides. And, as with any other new feature, you just need to learn how to use it.

That, combined by the desire to be as efficient as possible which makes QStringBuilder to use const references instead of copying the QString object, makes it behave like this.

This can not break the existing code for two reasons – you don’t use auto in it, and you probably do not define the QT_USE_FAST_OPERATOR_PLUS macro before including QString.

Switching shells

A working mock for testing the underlying framework for Plasma shell switching:

video on youtube

RSI and a peculiar development setup contd.

RSI (Repetitive strain injury) is not an uncommon disorder in the geek world. It can range from a slight tiredness to a very unpleasant pain.

I don’t know how it should really be treated, but I know two things – it should not be ignored, and you should not, when you stop ignoring it, try to relax and rest your fingers by playing guitar after not playing it for more than a year. Air guitar should be fine if you don’t overdo it. :)

One of the first things I started doing as a precaution was to switch the mouse hand every once in a while, and to lessen the number of clicks by making a no-click application launcher.

The last step I took was a few days ago. Mainly because this summer is going to be very stressful for my hands, and my fingers don’t seem up to it at the moment. The last step was to remove the resistance of the keys on my keyboard. That is, to replace the keyboard with something else.

RSIstop

As you can see, I have replaced it with a virtual one (xvkbd) running on the exopc tablet under plasma active. It controls my main computer.

I expected it to be quite a productivity killer at first, but it turned out to be quite a pleasant exercise both for my hands (different motions, no resistance) and by mind (thinking of the shortest way to type a variable name by using the fuzzy completion of the vim’s YouCompleteMe plugin – haven’t typed more than three letters per variable in a whole day).

All in all, a rather fun setup. The only issue I’m having is that xvkbd is not meant for multi-touch so if somebody knows of a full-qwerty+special keys virtual keyboard that can be shown on one display and control a different one, I’d be much obliged.

Singletons, shared instances, the modern way

The last post showed how to create a modern and safe d-ptr (pimpl) idiom. There were a few questions regarding the purpose of such a thing, when you can directly use std::unique_ptr or QScopedPointer. The main reason is that it provides additional safeguards from abuse by making the interface minimal. Most importantly, it does not provide an interface to get the raw pointer. (note: it does, but if you are able and want to write something like delete d.operator->() who am I to stop you)

Today, we’ll talk about something evil – singletons. Or, more precisely, the lesser evil brother of a singleton that lasts only while someone holds a pointer to it. Again, it is not something that is difficult to implement, even in old C++, but thanks to the new smart pointers of C++11 it starts to be more elegant.

template <typename Target>
class shared_singleton {
public:
    static std::shared_ptr<Target> instance()
    {
        auto ptr = s_instance.lock();
 
        if (!ptr) {
            ptr = std::make_shared<Target>();
            s_instance = ptr;
        }
 
        return ptr;
    }
 
private:
    static std::weak_ptr<Target> s_instance;
};
 
template <typename Target>
std::weak_ptr<Target> shared_singleton<Target>::s_instance;

There’s room for improvement (thread safety, interface), but it works quite well as it is.

And yes, I’m aware that it can be done with Qt’s pointer classes, or QShared* ones. :)

Splashed across plasma

In order to have an elegant way of switching plasma shells at runtime, we need to hide the process from the user. Is there a nicer way of doing that than showing a pretty splash screen on top of everything? (this is a rhetoric question – don’t answer, it has already been decided)

:)

This is aimed at Plasma Workspaces 2 and is pure Qt5/QML2 thingie. It will also be used as a base for the future versions of KSplashQML (aka TSP).

Here’s the obligatory looped gif showing what it looks like.

splash