Sunday, 4 September 2016

What you need _not_ know about std::function - Part 2


  • Part-1 : Getting to know the basics
  • Part-3 : Performance benchmarks


In the previous post we saw some basic type traits and metafunctions that are used in the implementation of std::mem_fn and std::function.  The main gist of this post is to understand the implementation of std::function in libstd++.

Also, I would have liked to talk about things like:
  • The performance penalty of using std::function.
  • When to use std::function.
  • Some performance benchmarks.
I will leave the above topics as the centre of discussion in the third part of the series (This was supposed to be the sentinel post as per my original plan).  Discussing them here will just make this post a torture to read.

A naive implementation

Library development in C++ is tough. It becomes even more intricate when it is supposed to be generic. The most difficult part or rather detail oriented part is the type system itself. Dealing with the types together with their qualifications results in lot of metaprogramming boilerplate code and if you forget something it could lead to some nasty UB.

So, let's first try to implement our own but rather very simple version of std::function. I will be skipping a-great-many required details to keep the code small.

The requirements

1. Should be able to invoke any callable target.
2. The underlying type of the callable object must be hidden i.e the only type information that should be visible is the pure function signature only.
3. The target callable object must be valid as long as the function object is valid.

I have kept bare minimum requirements for my implementation to keep off from doing metaprogramming hackery which we would be seeing anyways while going through the implementation of std::function.

The first attempt

This version just implements the basic interface of Function and also implements the specialization for function pointer. In the later versions (or attempts), the interface developed for Function would more or less remain the same only the specialization required to handle other types of callable objects would be handled.

template <typename> class Function;

template <typename Ret, typename... Args>
class Function<Ret(Args...)>
{
public:
  using implementation = detail::function_impl_base<Ret, Args...>;

  //Default constructor
  Function() = default;

  template <typename Callable>
  Function(Callable f): // Requires callable be copyable
    impl_base_(std::make_unique<detail::func_impl<Callable>>(
                   std::move(f), detail::constructor_tag()))
  {}

  // Copy constructor
  Function(const Function& other)
  {
    this->impl_base_.reset(other.impl_base_->clone());
  }

  // Copy Assignment
  Function& operator=(Function other)
  {
    this->impl_base_.reset(other.impl_base_.release());
    return *this;
  }

  template <typename Callable>
  Function& operator=(Callable cb)
  {
    this->impl_base_ =
      std::make_unique<detail::func_impl<Callable>>(
                std::move(cb), detail::constructor_tag());
    return *this;
  }

  Ret operator()(Args&&... args)
  {
    assert (impl_base_.get());
    return (*impl_base_)(std::forward<Args>(args)...);
  }

private:
  std::unique_ptr<implementation> impl_base_ = nullptr;
};

Nothing much fancy. We have the same signature as that of std::function i.e the type Function is not aware about the type of the call target. That means that for function pointer or member function pointer or functor, the syntax of the Function object declaration would be exactly the same (provided the function signature is same of course) even though the actual types of all these callable objects are different. This is achieved using a technique called 'Type Erasure'.

Type Erasure

I am not intending to explain type-erasure in detail here. There are already a lot of content on it floating on the web. boost::any is one of the very basic example of type-erasure. shared_ptr, std::function are the other that I know of in the standard library that makes use of this technique.

Type-erasure in it's basic form is implemented by making use of polymorphism and thus requires dynamic memory allocation. This is how my implementation of Function does the type-erasure.

In the above code function_impl_base is the base class defining the interface. The derived classes implementing the specializations for different types of Callable types must implement the functions provided by the interface.

namespace detail {

  struct constructor_tag {};

  template <typename Ret, typename... Args>
  class function_impl_base
  {
  public:
    virtual Ret operator()(Args&&... args) const = 0;
    virtual function_impl_base* clone() = 0;
    virtual ~function_impl_base() {}
  };

  template <typename T> class func_impl;

  // Specialization for Function pointers
  template <typename Ret, typename... Args>
  class func_impl<Ret(*)(Args...)> final : public function_impl_base<Ret, Args...>
  {
  public:
    using callable_t = Ret(*)(Args...);

    /*
     * This is a greedy constructor. constructor_tag is just used so as
     * to not interfere with regular copy-constructor.
     */
    template <typename F>
    func_impl(F&& callable, constructor_tag): callable_(std::move(callable))
    {}

    func_impl(const func_impl&) = default;

    func_impl& operator=(func_impl&) = default;

    Ret operator()(Args&&... args) const
    {
      return callable_(std::forward<Args>(args)...);
    }

    func_impl* clone()
    {
      return (new func_impl(*this));
    }

  private:
    callable_t callable_;
  };

}


Let's now look at the constructor of Function in a bit more detail:
template <typename Callable>
  Function(Callable f): // Requires callable be copyable
    impl_base_(std::make_unique<detail::func_impl<Callable>>(std::move(f), detail::constructor_tag()))
  {}

The constructor is a template constructor and is the only part of  Function class (lets forget about assignment and copy constructors for the time being) which actually knows about the type of the callable object. But this knowledge is lost as soon as the constructor exits. But, we need to save this information in some form, right ? This is where inheritance comes into picture. Using inheritance, the type of the information is saved as RTTI (Run Time Type Information) probably in the vtable. This is exactly the purpose of function_impl_base.  
The class func_impl<Ret(*)(Args...)>  inherits from function_impl_base and implements the call operator.

The final attempt

Not much difference, only added specialization for member function pointer and functors:

namespace detail {

  template <typename Ret, typename... Args>gt;
  class function_impl_base
  {
  public:
    virtual Ret operator()(Args&&... args) = 0;
    virtual function_impl_base* clone() = 0;
    virtual ~function_impl_base() {}
  };

  template <typename Signature, typename Functor>gt; class func_impl;

  // Specialization for Function pointers
  template <typename Ret, typename... Args>gt;
  class func_impl<Ret(Args...), Ret(*)(Args...)>gt; final
            : public function_impl_base<Ret, Args...>gt;
  {
  public:
    using callable_t = Ret(*)(Args...);

    // The need for constructor tag removed in this version
    func_impl(callable_t callable): callable_(std::move(callable))
    {}

    func_impl(const func_impl&) = default;

    func_impl& operator=(func_impl&) = default;

    Ret operator()(Args&&... args)
    {
      return callable_(std::forward<Args>gt;(args)...);
    }

    func_impl* clone()
    {
      return (new func_impl(*this));
    }

  private:
    callable_t callable_;
  };

  // Specialization for Functors
  template <typename Functor, typename Ret, typename... Args>gt;
  class func_impl<Ret(Args...), Functor>gt;
            : public function_impl_base<Ret, Args...>gt;
  {
  public:
    using callable_t = Functor;

    func_impl(Functor callable): callable_(std::move(callable))
    {}

    func_impl(const func_impl&) = default;
    func_impl& operator=(func_impl&) = default;

    Ret operator()(Args&&... args)
    {
      return callable_(std::forward<Args>gt;(args)...);
    }

    func_impl* clone()
    {
      return (new func_impl(*this));
    }

  private:
      callable_t callable_;
  };

  // Specialization for Member function pointers
  // Leveraging the use of mem_fn
  template <typename Class, typename Member, typename Ret, typename... Args>gt;
  class func_impl<Ret(Args...), Member Class::*>gt;
            : public function_impl_base<Ret, Args...>gt;
  {
  public:
    using callable_t = Member (Class::*);

    func_impl(callable_t callable): callable_(std::move(callable))
    {}

    func_impl(const func_impl&) = default;
    func_impl& operator=(func_impl&) = default;

    Ret operator()(Args&&... args)
    {
      return call(std::forward<Args>gt;(args)...);
    }

    template <typename ClassType, typename... Params>gt;
    Ret call(ClassType obj, Params&&... args)
    {
      return std::mem_fn(callable_)(obj, std::forward<Params>gt;(args)...);
    }

    func_impl* clone()
    {
      return (new func_impl(*this));
    }

  private:
    callable_t callable_;
  };

}

template <typename>gt; class Function;

template <typename Ret, typename... Args>gt;
class Function<Ret(Args...)>gt;
{
public:
  using implementation = detail::function_impl_base<Ret, Args...>gt;;
  using call_signature = Ret(Args...);

  //Default constructor
  Function() = default;

  // Copy constructor
  Function(const Function& other)
  {
    this->gt;impl_base_.reset(other.impl_base_->gt;clone());
  }

  // Copy Assignment
  Function& operator=(Function other)
  {
    this->gt;impl_base_.reset(other.impl_base_.release());
    return *this;
  }

  template <typename Callable>gt;
  Function& operator=(Callable cb)
  {
    this->gt;impl_base_ =
      std::make_unique<detail::func_impl<call_signature, Callable>gt;>gt;(std::move(cb));
    return *this;
  }

  // constructor
  template <typename Callable>gt;
  Function(Callable f): // Requires callable be copyable
    impl_base_(std::make_unique<detail::func_impl<call_signature, Callable>gt;>gt;(std::move(f)))
  {
  }

  Ret operator()(Args&&... args)
  {
    assert (impl_base_.get());
    return (*impl_base_)(std::forward<Args>gt;(args)...);
  }

  explicit operator bool() const noexcept
  {
    return impl_base_ != nullptr;
  }

private:
  std::unique_ptr<implementation>gt; impl_base_ = nullptr;
};
  

The above code can be accessed from HERE.

Issues with the custom implementation

1. Memory allocation. Dynamic memory allocation is costly. It is probably ok if you know you are not going to create many instances of Function object and pass it around. But it's a big no-no in a performance critical code. This can be resolved in some cases by doing SBO (Small Buffer Optimization), which is what almost all implementation does.

2. No type checking at all. Since the type of the actual callable object gets erased after constructor and assignment operators. It is better to check whether the user is correctly using the function object. If not, it should be a compile time error rather than leading to subtle undefined behaviour in the code.

3. Overhead of a virtual function call and that of an additional call to the callable object. This can be pretty bad, if you going to call your implementation functions via Function.

4. The cost of generic programming. This is my personal opinion, customized solution can be made faster than the above Function implementation, but when you have to use something like Function as part of your interface to client code, then this is the way we have to do and improve upon it. This is something which I would like to touch upon in the final part of this series.

The Implementation of std::function 

In this section we will see the implementation of std::function in libstd++ 6.1. We will be making use of some of the type traits discussed in Part-1 and will see some new ones here. Let's first lookup at some concepts and tricks individually and connect them up later.

Location Invariance

The metafunction for this check is:

template <typename T>
struct is_location_invariant
     : is_trivially_copyable<T>::type
{ };

This is one of the checks that is made to determine if SBO can be performed on the passed callable type or not. This is mainly relevant for Functors, since function pointer and member function pointers are trivially copyable. So, it is necessary that one must make sure that his/her functor implements the TriviallyCopyable concept.

For the lazy people (from cppreference) :
  • Every copy constructor is Trivial or deleted (since C++14)
  • Every move constructor is Trivial or deleted (since C++14)
  • Every copy assignment operator is Trivial or deleted (since C++14)
  • Every move assignment operator is Trivial or deleted (since C++14)
  • at least one copy constructor, move constructor, copy assignment operator, or move assignment operator is non-deleted
(since C++14)
  • Trivial non-deleted (since C++14) destructor
This implies that the class has no virtual functions or virtual base classes.
Scalar types and arrays of TriviallyCopyable objects are TriviallyCopyable as well, as well as the const-qualified (but not volatile-qualified) versions of such types.


No-Copy Types

This is nothing but the types of callables that does not need to be copied:

  class Undefined_class;

  union Nocopy_types
  {
    void*       M_object;
    const void* M_const_object;
    void (*M_function_pointer)();
    void (Undefined_class::*M_member_pointer)();
  };

This basically means, below types are no-copy types:-

  1. Pointer to a callable object.
  2. Pointer to a const callable object.
  3. A function pointer.
  4. A member function pointer.
The lack of any template parameters should give you an hint that the actual types mentioned inside the union is not going to be used. Maybe it's the size of the union ? We will get to that shortly.

Small Buffer Optimization

Let's see the data structure employed for the all important small buffer optimization by libstd++

  union Any_data
  {
    void*       M_access()       { return &M_pod_data[0]; }
    const void* M_access() const { return &M_pod_data[0]; }

    template <typename T>
    T& M_access() {
      return *static_cast <T*>(M_access()); 
    }

    template <typename T >
    const T& M_access() const {
      return *static_cast<const T*>(M_access());
    }
      
    Nocopy_types M_unused;
    char M_pod_data[sizeof(Nocopy_types)];
  };

It is just a char buffer having a size of sizeof(Nocopy_types) bytes, which should be 8 bytes on 64 bit platform. This is another constraint that the functor must have other than the location invariance,  for the implementation to perform SBO.
If the size of your functor is more than 8 bytes, then you will have to pay for one dynamic allocation.

The Function_base class

This class basically deals with the small buffer or Any_data directly. It makes the decision of what needs to be stored in Any_data i.e whether it should be the callable object as it is or the memory location of the callable object after allocating it on heap.

There are 2 inner classes named Base_manager and Ref_manager (a specialization for reference_wrapped functors), which does the actual dealing with Any_data.

Lets dig into the implementation of Base_manager, which would give us a lot of idea on what is happening behind the scenes.

      template<typename Functor>
      class Base_manager
      {
      protected:
        static const bool stored_locally =
        (is_location_invariant<Functor>::value
         && sizeof(Functor) <= M_max_size  // 8 bytes on 64 bit
         && alignof(Functor) <= M_max_align
         && (M_max_align % alignof(Functor) == 0));

        typedef integral_constant<bool, stored_locally> Local_storage;

        // Retrieve a pointer to the function object
        static Functor*
        M_get_pointer(const Any_data& source)
        {
          const Functor* ptr =
            stored_locally? std::addressof(source.M_access<Functor>())
            /* have stored a pointer */ : source.M_access<Functor*>();
          return const_cast<Functor*>(ptr);
        }

        // Clone a location-invariant function object that fits within
        // an _Any_data structure.
        static void
        M_clone(Any_data& dest, const Any_data& source, true_type)
        {
          new (dest.M_access()) Functor(source.M_access<Functor>());
        }

        // Clone a function object that is not location-invariant or
        // that cannot fit into an _Any_data structure.
        static void
        M_clone(Any_data& dest, const Any_data& source, false_type)
        {
          dest.M_access<Functor*>() =
            new Functor(*source.M_access<Functor*>());
        }

        // Destroying a location-invariant object may still require
        // destruction.
        static void
        M_destroy(Any_data& victim, true_type)
        {
          victim.M_access<Functor>().~Functor();
        }

        // Destroying an object located on the heap.
        static void
        M_destroy(Any_data& victim, false_type)
        {
          delete victim.M_access<Functor*>();
        }

      public:
        static bool
        M_manager(Any_data& dest, const Any_data& source,
                   Manager_operation op)
        {
         //skipped
         ........
        }

        static void
        M_init_functor(Any_data& functor, Functor&& f)
        { M_init_functor(functor, std::move(f), Local_storage()); }


      private:
        static void
        M_init_functor(Any_data& functor, Functor&& f, true_type)
        { new (functor.M_access()) Functor(std::move(f)); }

        static void
        M_init_functor(Any_data& functor, Functor&& f, false_type)
        { functor.M_access<Functor*>() = new Functor(std::move(f)); }
      };

Now that's something. The integral constant Local_storage is set to true if the functor can be stored inside the Any_data buffer else it will be false and the other member functions gets called based on that using tag-dispatching. For eg. check out the definitions for M_clone member function.

Let's look at functions M_init_functor and M_get_pointer in bit more detail to understand how the callable object is stored and retrieved by std::function.
 static void
 M_init_functor(Any_data& functor, Functor&& f)
 { M_init_functor(functor, std::move(f), Local_storage()); }

 static void
 M_init_functor(Any_data& functor, Functor&& f, true_type)
 { new (functor.M_access()) Functor(std::move(f)); }

 static void
 M_init_functor(Any_data& functor, Functor&& f, false_type)
 { functor.M_access<Functor*>() = new Functor(std::move(f)); }
 

Considering the passed callable object meets the requirement for being stored on stack, Local_storage would be of true_type, hence the second M_init_functor will get called, which makes use of placement new operator to construct the object on the stack itself.

If the callable object does not meet the requirement for being stored locally i.e it is either not TriviallyCopyable or has data members making its size more than what is allowed (i.e 8 bytes on 64 bit platform), then the callable object is created on heap and its memory location gets stored in the Any_data buffer. This is what the third M_init_functor function does.

 static Functor*
 M_get_pointer(const Any_data& source)
 {
   const Functor* ptr =
        stored_locally ? std::addressof(source.M_access<Functor>())
             : source.M_access<Functor*>();
   return const_cast<Functor*>(ptr);
 }

This must be now easier to reason about. Depending upon whether the callable object is stored locally or not, M_get_pointer gets the address of the callable object. The other member functions are just based upon this technique.

The Ref_manager is just basically a specialization to take care of functor passed via a reference_wrapper. Which is something one must consider to do if their function object size is greater than 8 bytes (on 64 bit platform) AND if the scope of the callable object outlives the scope of the std::function object.

So, having seen Base_manager and Ref_manager class, lets see how Function_base class looks like:

 class Function_base {
 public:     
   static const std::size_t M_max_size = sizeof(Nocopy_types);
   static const std::size_t M_max_align = alignof(Nocopy_types);

   template <typename Functor>
   class Base_manager { ... };

   template <typename Functor>
   class Ref_manager : public Base_manager <Functor*>
   {
     .....
   };

   typedef bool (*Manager_type)(Any_data&, const Any_data&,
                                Manager_operation);

   Any_data     M_functor;
   Manager_type M_manager;
 }; 

As one can see, Manager_type is a function pointer pointing to either Base_manager::M_manager or Ref_manager::M_manager function. These functions basically fill the destination Any_data with the stored callable object from the source Any_data based upon the operation. Something like below:

        static bool
        M_manager(Any_data& dest, const Any_data& source,
                  Manager_operation op)
        {
          switch (op)
          {
            case get_functor_ptr:
              dest.M_access <Functor*>() = M_get_pointer(source);
              break;

            case clone_functor:
              M_clone(dest, source, Local_storage());
              break;

            case destroy_functor:
              M_destroy(dest,Local_storage());
              break;
            }
          return false;
        }


Function Handlers

The function handlers are kind of similar in functionality to func_impl in my custom implementation i.e to invoke the actual callable object. The classes which we saw till now were to only manage the storage part, they were not concerned with invoking the call operator. 

Function handler classes are derived from either Function_base::Base_manager or Function_base::Ref_manager based upon the functor type. The function handlers are also specialized for plain function pointers, member pointers and for functors. 

We will be seeing only few of those specialization.

1. Specialization for plain function pointer.

    template<typename Signature, typename Functor>
    class Function_handler;

  template<typename Res, typename Functor, typename... ArgTypes>
    class Function_handler<Res(ArgTypes...), Functor>
    : public Function_base::Base_manager<Functor>
    {
      typedef Function_base::Base_manager<Functor> Base;

    public:
      static Res
      M_invoke(const Any_data& functor, ArgTypes&&... args)
      {
        return (*Base::M_get_pointer(functor))(
            std::forward<ArgTypes>(args)...);
      }
    };

2. Specialization for Member pointer.

   template<typename Class, typename Member, typename Res,
           typename... ArgTypes>
    class Function_handler<Res(ArgTypes...), Member Class::*>
    : public Function_handler<void(ArgTypes...), Member Class::*>
    {
      typedef Function_handler<void(ArgTypes...), Member Class::*>
        Base;

     public:
      static Res
      M_invoke(const Any_data& functor, ArgTypes&&... args)
      {
        return std::mem_fn(Base::M_get_pointer(functor)->value)(
            std::forward<ArgTypes>(args)...);
      }
    };

This is very similar to what we did for member pointers in our custom implementation i.e let std::mem_fn do the heavy lifting of taking care of both member data pointer and member function pointer.


Design uptill now

Specialization of a regular functor is also not much different than what we saw for plain function pointer. The design is like below:
1. Function_base is responsible for storing and retrieving the pointers to the callable object.
2. The function handler objects fetches the pointer to the callable objects from Function_base and invokes them with the passed arguments.

The std::function class

This is  what we all have been waiting for.But, you would be surprised (or not) to know that we have already covered all the heavy lifting part ! function class is more about the interface it provides, the type checkings and conversions.

The basic interface is pretty close to what we implemented in our custom solution, so we will be only looking at the interesting parts i.e the things we left out from our custom implementation.

A stripped down version of std::function:

 template < typename Res, typename... Args >
 class function<Res(Args...)>
     : private Function_base
 {
   typedef Res Signature(Args...);
 public:
   function(): Function_base() {}

   template <typename Functor,
                typename = Requires<not<is_same<Functor, function>>, void>,
                typename = Requires<Callable<Functor>, void>>
   function(Functor);

   Res operator()(ArgTypes... args) const;

 private:
   using _Invoker_type = Res (*)(const Any_data&, ArgTypes&&...);
   Invoker_type M_invoker;
 };

 template <typename Res, typename... ArgTypes>
 template <typename Functor, typename, typename>
 function<Res(ArgTypes...)>::
 function(Functor f)
      : Function_base()
 {
      typedef Function_handler <Signature, Functor> My_handler;

      My_handler::M_init_functor(M_functor, std::move(f));
      M_invoker = &My_handler::M_invoke;
      M_manager = &My_handler::M_manager;
 }


This is the part of code which I found pretty interesting. It is interesting because, it does not make use of inheritance the way we used in our custom implementation. With this kind of implementation, it is not required to do any dynamic allocation unless required because of the nature of functor.

The Functor parameter will determine what kind of Function_handler class we need to use. The invoker, which is a function pointer will be set to the correct M_invoke function of the function handler.
Thus, a single call to a callable object would require at most 2 pointer dereferences, no virtual calls and no dynamic allocation (depending on your Functor as we have already seen).

Type checking on assigning target

If we look at the constructor (or copy or assignment) template parameters a little bit more closely, we will see something like:
Callable <Functor>

Let us see what it is:
 template<typename From, typename To>
 using check_func_return_type
      = or<is_void<To>, is_same<From, To>, is_convertible<From, To>>;

 template<typename Func,
          typename Res2 = typename result_of<Func(ArgTypes...)>::type>
 struct Callable : check_func_return_type<Res2, Res> { };

The idea is to check whether the provided callable type yields a return type (Res2) when invoked with the argument types passed as the template parameters of std::function and that return type i.e Res2 is compatible with what was provided in the std::function declaration or in its template parameter.

The reason for adding is_same is pretty interesting. For details check THIS bug report.

I am not sure why is_convertible is required since its failure would not result in lookup of a constructor with different signature as there is only one definition of the constructor. The only advantage I see is, any wrong usage of std::function i.e. assigning it with a target with incompatible arguments would result in error thrown at the constructor itself, rather than at the calling site. If anybody knows about any other advantage, then please do let me know.

For example, see the usage of func1 and func2 and the error it yields using both my custom implementation (which does not use conversion checks) and std::function.

Error with My implementation:
./my_function.hpp:72:14: error: ambiguous conversion from derived class 'D' to base class 'A':
    struct D -> struct B -> struct A
    struct D -> struct C -> struct A
      return callable_(std::forward<Args>(args)...);
             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As one can see, the error is thrown at the point where we are actually invoking the callable target. This is not good since it is pointing an issue in the library implementers code, which is actually not the case. A good C++ library must try its best to point the error in the users code rather than to its own internal implementation.

inheritance.cc:45:5: error: no viable overloaded '='
  f = func2;
  ~ ^ ~~~~~
It points to the user code which messed it up. This is one nice advantage of using is_convertible which assigning a target.

A note about libcxx

The libcxx implementation of std::function looked a lot more straightforward than the libstd++ implementation and they provide a buffer size of 24 bytes (on 64 bit arch) for the SBO, which is 3 times more than what libstd++ offers. Also, libcxx supports allocator other than global new (I am not sure whether standard mandates that or not till c++14), which libstd++ does not currently.

Another difference w.r.t libstd++ is that the libcxx version makes use of virtual function call instead of function pointer as in libstd++. Now, I wouldn't state that function pointer would perform faster than a virtual function call, but I remember seeing the performance measurements of both types of call and a call via function pointer was slightly faster than a virtual function call.  Now, don't get all paranoid by that, as we will see in the final part of the blog series, std::function should better be not present in a tight code where performance matters most. In all other cases, the difference (if at all) shouldn't matter at all.

One problem that I see with non-standard way of implementing SBO is performance regression when going from one standard library implementation to another i.e. while moving from a library implementation that has larger internal buffer size than to a one having less (eg: libc++ -> libstd++). This would certainly waste quite some time of the developer who is debugging the issue (as in most cases this developer would not be the one who wrote the code :))





Friday, 24 June 2016

What you need _not_ know about std::function - Part 1


  • Part-2 : Implementation of std::function
  • Part-3 : Performance benchmarks


std::function is cool. No doubt about that. It provides you with a constant interface to create callable objects irrespective of whether it is constructed from a function pointer or member function pointer or functor or functionoid. I assume that everyone who is reading this have used it at least once. The mechanics of how it actually works is near magic.

In this post and in the second part of it, I will try my best to dissect the functional header file provided by libstd++. This post will be covering the basic type traits that will be required, std::mem_fn, few other technical stuff and in the next post I will discuss about the implementation of std::function.

The only part I am not going to touch from that file is std::bind. It's dark magic. Let's leave it at that.

Few notes:
1. The code would mostly be the prettified version of libstd++ implementation.
2. No guarantee about the correctness of my understanding. Comments are welcome if you see anything wrong in the explanation.



Some Basic Definitions

A expression for a function call as defined by the standard is
postfix-expression ( expression-list <optional> ) 
Few important definitions from the standard (Section 20.8.*)

1. Function Object Type is an object having the type of postfix-expression in the function call expression (see above).
2. Function Object is just an object of function object type.
3. Call Signature is the name of a return type followed by a parenthesized comma-separated list of zero or more argument types.
Example: Consider the function:
int foo (char c) {...}
Call signature for the above is:
int (char);
4. A Callable Type is a function object type or a pointer to member.
5. A Callable Object is an object of a callable type.
6. A Call Wrapper Type is a type that holds a callable object and supports a call operation that forwards to that object.
Below shows a very simple (but useless) example of such a call wrapper:
/* 
A wrapper around a callable type which
returns a void and takes an int.
*/
struct VoidCallWrapper {
  void operator()(int v) {
    callable_(v);
  }

  CallableType callable_; // Target Object
};
7. A Call Wrapper is an object of call wrapper type.

8. A target object is the callable object held by a call wrapper.

As you see, unlike 'C' which has only one callable type that I know of which is a function pointer, C++ has lot more variety of callable types:
1. Function pointer
2. Member function pointer
3. Member data
4. Functor
5. Functionoid

Having so many options definitely gives more flexibility, but at the same time can cause a lot of inconvenience due to difference in their syntaxes. One can easily use a template to hide the syntax differences and as we will see later that's what one should do when we do not need a stored callable object. But, when we need to store a callable object and which must remain valid across call stacks, we should use std::function. It has only the call signature as part of its type information, all the rest is erased (type-erasure). So, it is kind of a generic function pointer. All this would be the meat of discussion in one of the coming sections. 

Deep Dive into Type-Traits

Type traits are basically compile time introspection mechanism for getting some characteristics about the passed type (Mostly as a template parameter).
A quick example of a type-trait which checks whether the passed type has a member-type named value_type:

template <typename... T>
using void_t = void;

template <typename T, typename = void_t<>>
struct has_value_type : std::false_type {};

template <typename T>
struct has_value_type<T, void_t<typename T::value_type>> :
  std::true_type {};

int main() {
    static_assert (!has_value_type<int>::value, "Integer cannot have a value type!!");
    static_assert (has_value_type<std::string::iterator>::value, 
                                                  "String iterator must have value_type!!");
    return 0; 
}

The example shown makes use of the void_t trick.

Now, let's understand the type_traits used by std::mem_fn and std::function one by one.

NOTE: Not all the specializations for a type-trait would be covered in this post. The specializations for c-v qualification(s) and varargs are omitted for the sake of clarity and less typing.

Result Type for a Callable Type

A type-trait to know what the callable type returns when its object is called.
template<typename Functor>
struct Weak_result_type
    : Weak_result_type_impl<Functor>
{ };


As said earlier, the template has magically removed all the syntax differences between different callable types. All the type specific details are found out by doing partial specialization of Weak_result_type_impl struct for each callable type:

1. Specialization for regular function call signature
template <typename Res, typename... ArgTypes>
struct Weak_result_type_impl <Res(ArgTypes...)>
{ typedef Res result_type; };

This is simple, the partially specialized template parameter has pretty much the same signature of that of the call expression. The template argument deduction settles in for this specialization because it matches best (OR no other specialization matches) for a simple function.

Let's see an example of how this would work:
// This is not how the actual definition of Weak_result_type_impl
// is. It's just here for example.
template <typename F> struct Weak_result_type_impl;

template <typename Res, typename... ArgTypes>
struct Weak_result_type_impl <Res(ArgTypes...)>
{ typedef Res result_type; };

template <typename Functor>
struct Weak_result_type
    : Weak_result_type_impl <Functor>
{ };

int foobar() {
  return 42;
}

int main() {
  static_assert (
       std::is_same<Weak_result_type<decltype(foobar)>::result_type, int>::value,  
               "foobar should always return an int!!");
  return 0;
}

This should give good idea on how the rest of the partial specializations would work.

2. Specialization for function reference
template <typename Res, typename... ArgTypes>
struct Weak_result_type_impl<Res(&)(ArgTypes...)>
{ typedef Res result_type; };

3. Specialization for function pointer
template <typename Res, typename... ArgTypes>
struct Weak_result_type_impl <Res(*)(ArgTypes...)>
{ typedef Res result_type; };

4. Specialization for member function pointer
template <typename Res, typename Class, typename... ArgTypes>
struct Weak_result_type_impl <Res (Class::*)(ArgTypes...)>
{ typedef Res result_type; };

5. Specialization for Functor having a result_type  as a member type
template <bool Has_result_type, typename Functor>
struct Maybe_get_result_type {};

template <typename Functor>
struct Maybe_get_result_type <true, Functor>
{ typedef typename Functor::result_type result_type; };

template <typename Functor>
struct Weak_result_type_impl
    : Maybe_get_result_type <has_result_type<Functor>::value, Functor>
{ };

So, for a functor, it is important for that functor to have a member type called result_type in order for this type trait to work. 
Well, that's kind of not-so-generic, isn't it ? Yeah, there are other ways to get the result_type from a functor:
template <typename T, typename = void_t<>> struct Functor_return_type {};

template <typename T, typename... Args>
struct Functor_return_type<T(Args...),
                           void_t<decltype(
                                    std::declval<T>().operator()(
                                                    std::declval<Args>()...
                                  )  )
                           >>
{
 using result_type = decltype(std::declval<T>().operator()(std::declval<Args>()...));
};

class Functor {
public:
  int operator()(int v) {
    return 42;
  }
};

int main() {
  static_assert (std::is_same<Functor_return_type<Functor(int)>::result_type, int>::value, "");
  return 0;
}

This is somewhat what std::result_of does which is bit more complicated than what we have done here. So, the point was just to show that there are ways to get the return type from the functor or target callable object, but with a different interface (We had to provide expected argument types for the above.).

6. Metafunction to check if all is true

This basically means to check if all the checks passed into a metafunction evaluates to true or not. libstd++ makes use of '__and_', but here we will make use of the bool-trick, which I found here on StackOverflow.
template <bool... B>
struct bool_pack {};

template <bool... V>
using all_true = std::is_same<bool_pack<true, V...>, bool_pack<V..., true>>;

We will see a use case for it soon.

7. Metafunction to check if parameters passed are convertible to another.

We do have a standard meta function std::is_convertible<From, To> which evaluates to true if type From is implicitly convertible to To.

AllConvertible meta function works for variadic sets of template parameters and evaluates to true if and only if all the parameters provided in the first set are convertible into its respective parameters provided in the second set.
// To store the parameters as a list
template <typename... T> 
struct Pack : std::integral_constant<size_t, sizeof...(T)>
{};

template <typename From, typename To, bool = From::value == To::value>
struct AllConvertible : std::false_type
{ };

template <typename... From, typename... To>
struct AllConvertible<Pack<From...>, Pack<To...>, true>
    : all_true<std::is_convertible<From, To>...>
{ };
 

8. Metafunction Require

Require metafunction takes in a set of checks (same as bool-trick), but will fail to compile if any of the checks is false. Thus can be used as SFINAE, but maily used in mem_fn and std::function as hard compile time errors.
template <typename... Cond>
using Require = typename std::enable_if<all_true<Cond...>::value>::type;

What is std::mem_fn ?

In C++, for a class/struct, we can have pointers to its member functions and also pointers to its data members. Unlike regular function pointers, member function pointer is useless without an object to invoke it on. So, whenever you have the case for using member function pointer as a callback, one has to also provide the instance on which it needs to be called on. And, if you are in a situation wherein you want to make use of a pointer to a data member, you would have to use a slightly different dereferencing syntax. Also, member function/data pointers syntax are not pretty things to look at, but that's a secondary problem.

So, what mem_fn provides us is a consistent interface to create a callable object for both member function pointer and member data pointer.
What we get from that ? We can use it with STL algorithms now:
class Test {
public:
  void take() {
    std::cout << "Passed\n";
  }
};

int main() {
  std::array<Test, 3> arr = {Test(), Test(), Test()};
  std::for_each(std::begin(arr), std::end(arr), std::mem_fn(&Test::take));
  return 0;
}

It wouldn't be this easy (and beautiful) had we used raw member function pointers. 
Wait, I lied, there is a much more elegant way (and preferred) to do this using lambda expression:
  std::for_each(std::begin(arr), std::end(arr), [](const Test& t){ t.take(); });

Now, since mem_fn returns a callable object, it can also be used with std::function. 


std::mem_fn Implementation details


mem_fn is a template function and has the below signature:
template <typename Tp, typename Class>
Mem_fn<Tp Class::*>
mem_fn(Tp Class::*) noexcept;

It takes in a member function pointer or a member data pointer and returns an object of template class Mem_fn (capital 'M').

Definition of mem_fn:
template <typename Tp, typename Class>
Mem_fn <Tp Class::*>
mem_fn(Tp Class::* pm) noexcept
{
  return Mem_fn<Tp Class::*>(pm);
}

Pretty much the stuff explained before, nothing interesting. The interesting part would be to see, how Mem_fn provides a consistent interface for both member function pointers and member data pointers.

In the real implementation Mem_fn has several specializations  to deal with c-v qualifications, but as mentioned before, we will be looking at only one specialization i.e the one without c-v qualification involved. 

Also, Mem_fn is partially specialized to deal with pointers to member function and pointers to data members. This is how it provides a consistent call operator for both member function pointer and member data pointer.

Specialization for Member function

template <typename T> class Mem_Fn;

template <typename RetType, typename Class, typename... ArgTypes>
class Mem_Fn<RetType (Class::*) (ArgTypes...)>
{
  using Functor = RetType (Class::*) (ArgTypes...);

public:
  explicit Mem_Fn(Functor mf): func_(mf) { }

  // Handle lvalue reference to an object
  template <typename... Args,
            typename _R_ = AllConvertible<Pack<Args...>, Pack<ArgTypes...>>
           >
  RetType operator()(Class& obj, Args&&... args)
  {
    return (obj.*func_)(std::forward<Args>(args)...);
  }

  // Handle Rvalue reference
  template <typename... Args,
            typename _R_ = AllConvertible<Pack<Args...>, Pack<ArgTypes...>>
           >
  RetType operator()(Class&& obj, Args&&... args)
  {
    return (std::move(obj).*func_)(std::forward<Args>(args)...);
  }

  // Handle plain pointer to an object
  template <typename... Args,
            typename _R_ = AllConvertible<Pack<Args...>, Pack<ArgTypes...>>
           >
  RetType operator()(Class* obj, Args&&... args)
  {
    return (obj->*func_)(std::forward<Args>(args)...);
  }

  // Handle reference wrapper
  template <typename T, typename... Args,
            typename _R_ = AllConvertible<Pack<Args...>, Pack<ArgTypes...>>,
            typename std::enable_if<std::is_base_of<T, Class>::value>::type* = nullptr
           >
  RetType operator()(std::reference_wrapper<T> ref, Args&&... args)
  {
    return operator()(ref.get(), std::forward<Args>(args)...);
  }

  // Handle smart pointer
  // Maybe sometime later...... :)


private:
  // The member function pointer
  Functor func_;
};

With the knowledge of the type-traits we saw earlier it should be pretty easy to follow the template constraints put on the member functions. This is onle of the ways how c++ template metaprogramming offers tight type system checks.

Behaviour with Ref Qualified member functions

This is pretty basic stuff, except for one important behaviour/optimization which I surely would have missed implementing (but actually doesn't work, see next para) had I have had to implement this class.  Here, I am specifically talking about the overload for rvalue reference. Notice how the member function is called on the moved object:
 return (std::move(obj).*func_)(std::forward<Args>(args)...);

At first I expected it to call the rvalue ref-qualified version of the function (if provided of course). But that does not seem to be the case. The ref-qualifiers are tightly bound to the member function signature and unless explicitly provided, it would not call it.
Checkout this SO question for more details.


A peek into std::function

As the holy standard puts it:
The function class template provides polymorphic wrappers that generalize the notion of a function pointer. Wrappers can store, copy and call arbitrary callable objects, given a call signature, allowing functions to be first-class objects.
In the next section we will go about seeing how std::function is really implemented. So, stay tuned...

Part-2 of the series is HERE !

Saturday, 19 March 2016

Sub-processing with modern C++

Now and then developers usually find themselves with a requirement to execute shell commands or launch other processes from their code. Usually for such tasks, the target OS provides API/system calls to achieve the same. For example, Linux offers many ways via its system calls and C library/libc, execl, execle, execlp, execv, execvp, execvP, system, popen etc. Many of which may execute the provided command using shell which has its own set of security concerns. And when it comes to chaining two or more commands via piping or monitoring the running process things become quite low level and error prone. This is where the sub-processing library swoops in.

Python subprocess module

The whole idea of creating a subprocess module for C++ came from python subprocess module. Specifically the one distributed with 2.7 version of python.
It has become the defacto module for executing commands in python. It offers a rich set of API's which can be used to achieve various functionalities such as 
  1. Switch to execute a command from shell or without it.
  2.  Redirection of standard input/output/error streams.
  3.  Piping/Chaining multiple commands.
  4.  Interacting with the child process by sending messages to it standard input channel.
  5.  Streamed/block reading of the output.
  6.  Monitoring the process using poll / wait functions.
  7.  Running user defined functions before exec'ing the child.
  8.  Low level details such as working with pipes, file descriptors etc is completely wrapped.
These are few of the features that just came off from the top of my head. For having a more detailed look at it, checkout :

C++ subprocess module

Now, I looked around quite a bit for finding something similar and lightweight for C++ and surprisingly I did not find anything except for Boost.Process, but for some reasons it never got into boost and I somehow didn't like the way the source was written. Looked a bit complicated for the task at hand.
Also, with the modern C++ standard (C++11 to be precise), we can actually obtain syntax similar to python. So, with python subprocess as reference and with C++11 compiler support, I came up with my own version of subprocess module.


Examples

I will directly jump into examples since there is no point explaining how this works. It's just a basic fork-exec stuff with quite a bit low level stuff.

To run a simple command without any extra interaction, just like system call


#include "subprocess.hpp"
namespace sp = subprocess;
auto ret = sp::call({"ls", "-l"});


Now, if we want to run the same command by spawning the shell process and then passing the command to shell, the just do:

auto ret = sp::call({"ls", "-l"}, shell{true});

We have just set the shell parameter to true. As you can see, the way we are passing arguments are quite different. We will talk about/see more of it later.

Just for the sake of comparison, here is what a python program would look like:

import subprocess as sp
ret = sp.call(["ls", "-l"], shell=True)

Almost similar, isn't it ?

Below example shows how to get the output :

auto obuf = check_output({"ls", "-l"}, shell{false});
std::cout << obuf.buf.data() << std::endl;

check_output returns the data collected at the output stream of the process and returns it after the command is executed.
obuf is of type Buffer. It looks almost something like below:

struct Buffer {
  std::vector<char> buf;
  size_t length = 0;
};

This structure is being used instead of plain vector because of the dynamic resizing (not reserve) of the vector which does not tell how many bytes of data were actually written into it.

We can also check the return code of the executed command via retcode function.
But, for that one will have to use Popen class.

auto p = Popen({"ls", "-l"}, shell{true});
int ret = p.retcode();

Now, let's see an example of redirection. Here, we will redirect the error channel to output channel.

auto p = Popen("./write_err.sh", output{"write_err.txt"}, error{STDOUT});

write_err.sh is a script that just writes to stderr. output channel is set to write to a file named write_err.txt and error channel is redirected to output channel i.e to 'write_err.txt' file.

Piping In & Piping Out

Python subprocess supports pipelining in a very intuitive way by allowing successive commands to set their input channels to output channel of previous command. This library also supports that kind of pipelining but also takes the syntax (it terms of easiness) to another level.

As an example, take below unix/linux command as an example:
cat subprocess.hpp | grep template | cut -d, -f 1

Translating to cpp-subprocess:


auto cat  = Popen({"cat", "subprocess.hpp"}, output{PIPE});
auto grep = Popen({"grep", "template"}, input{cat.output()}, output{PIPE});
auto cut  = Popen({"cut", "-d,", "-f", "1"}, input{grep.output()}, output{PIPE});
auto res  = cut.communicate().first;
std::cout << res.buf.data() << std::endl;

This is pretty much the same thing you would do in python as well. But, by making use of variadic templates we can chain these commands and make pipelining look like:

auto res = pipeline("cat subprocess.hpp", "grep Args", "grep template");
std::cout << res.buf.data() << std::endl;

Does that make anyone happy ?

Working with environment variables

Let's see an example directly:


int st= Popen("./env_script.sh", environment{{
                                        {"NEW_ENV1", "VALUE-1"},
                                        {"NEW_ENV2", "VALUE-2"},
                                        {"NEW_ENV3", "VALUE-3"}
                                  }}).wait();

It's more about the syntax.

Other options supported are:
  1. executable - To set the executable.
  2. cwd           - To set the current working directory.
  3. bufsize      - Sets the buffer size of input/output/error streams.
  4. environment - Sets the environment variables required by spawned process.
  5. defer_spawn - Defer the spawning of process. Start it explicitly with start_process function.
  6. shell             - Execute with shell.
  7. input            - Sets the input channel.
  8. output          - Sets the output channel.
  9. error            - Sets the error channel.
  10. close_fds     - Flag to indicate whether all file descriptors needs to be closed before exec'ing.
  11. preexec_func - User define function to be executed before execing.
  12. session_leader - Flag to indicate whether the spawned process must be session leader or not.
Most of them are similar to what python subprocess module supports. So, it would be better to read it's documentation as well as it would be more exhaustive.

About the library

  1. Does not support Windows. Do not have any expertise with working on Windows.
  2. Exception handling is still primitive.
  3. Need to add more and more tests.
  4. Needs C++11 support to compile.
  5. Tested on Linux/Ubuntu and Mac OS with g++-4.8 and clang 3.4 compiler resp.

Sunday, 20 September 2015

Slicing in C++

For the last few days, I have been playing around with Go language. I was basically doing the algorithms part so that I could in parallel write a concise yet beautiful code in its c++11 version as well (but you know thats quite ironic..). So, it was pretty much useless thing, but I wanted to do it anyways just for the fun part. That means, don't blow me away if you don't see me using any standard library functions for achieving something which I am intending to do.


Slices in Go

If you have not yet crossed your path with Go (I suggest you do), slices are basically your 'std::vector' counterpart in Go. Now there is a huge difference technically, but it is still a data structure which you would choose in Go if you are to store elements in memory contiguously.

Slices in Go abstracts away the underlying representation of the container actually storing the elements. But, it is usually an array, because thats what you want to store elements in contiguous memory location.

You can get down to its basics by reading through the below link:

Now what can you do with this slices ? Well, lets see this below example:

func edit_slice(elems []int) {
    for idx, _ := range elems {
        elems[idx] += 3
    }
}

func main() {
    elems := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    edit_slice(elems[len(elems)/2:])
}

This is a pretty simple code which does nothing but increment each element from the last half by 3. It need not have been the last half, it could have been any 'range' (There is a reason why I have marked it as bold. Will come to that soon).

Now, lets see how someone would do that in c++11:
#include <vector>
#include <algorithm>

void edit_elems_1(std::vector<int>& vec,
                  std::vector<int>::iterator it1,
                  std::vector<int>::iterator it2)
{
    for (; it1 != it2; it1++) {
        *it1 += 3;
    }
}

void edit_elems_2(std::vector<int>& vec)
{
    std::for_each(vec.begin() + vec.size()/2, vec.end(),
                  [&](int& elem) { elem += 3; } );
}


int main() {
    std::vector<int> vec{1,2,3,4,5,6,7,8,9,10};
    edit_elems_1(vec, vec.begin() + vec.size()/2, vec.end());
    edit_elems_2(vec);
    return 0;
}

This time 'std::for_each' came to our rescue, otherwise it looks terrible ('edit_elems_1'). Even the 'std::for_each' is a bit harsh on the eyes compared to Go version.

Ranges in C++


But, this is not just me who is complaining about the inflexibility of 'iterators' in C++. Introducing the 'Range' concept is becoming more and more vocal in c++ world.

I believe it all started with the man 'Andrei Alexandrescu'. You can read through his 15 pages article to understand what he needs to convey:
http://www.informit.com/articles/article.aspx?p=1407357

Andrei implemented this concept in 'D' language. But our c++ experts wont accept defeat that easily, do they? We have got 'boost ranges' in answer to that. There is a series of posts by the author itself ('Eric Neibler') at his own weblog ('http://ericniebler.com/category/ranges/').

The implementation for the ranges in c++ seems to be very complex for me to comprehend right now. But there obviously has to be an easier way to implement what we can do in Go (or even python for that matter, but python is getting complex..huh, I will leave that for another talk).

So, what I have here is a POC for making use of slices in C++. There are many limitations in my design currently:
1) Not at all production ready. Its just a POC.
2) Some design issues. Adding new containers is bit contrived.
3) Many functionalities available in Go not yet supported.
4) Proper exception handling. With little more work it can be improved.
5) I am still not happy with the overall design. Did things in a hurry.

That said, I might not be continuing with this effort unless I really feel an urge to finish it off. So, If you guys think it would be cool or you think you have a much better way to do it, then surely let me know in the comments section.

Slices in C++

Lets just take a dive and see how an implementation of a naive binary search would look in Go and in C++ with my slice implementation.

Go binary search:
func binary_search_rec(arr []int, find int) bool {
    mid := len(arr) / 2

    if arr[mid] == find {
        return true
    }

    if mid == 0 {
        return false
    }

    if find > arr[mid] {
        return binary_search_rec(arr[mid+1:len(arr)], find)
    } else {
        return binary_search_rec(arr[0:mid], find)
    }
}

C++ binary search - with slices:
#include "slice.hpp" // My slice header

template <typename C>
bool binary_search(slice<C> slice, typename C::value_type val)
{
    int mid = len(slice)/2 ; 
                             
    if (slice[mid] == val) return true;
    if (mid == 0) return false;

    if (val > slice[mid]) return binary_search(slice(mid+1, end), val);
    else return binary_search(slice(beg,mid), val);
}

I am sure you can just take a guess and how it would look like without slices. So does this look anything close to 'cool' to you ? This technique can be used at all places where we want to operate on only a part of the data set at a time. Eg: QuickSort etc.

Also, note that the C++ version above just works well with a std::vector or std::string or std::array (Not testes, but should work), but thats not the gist of this comparison, its the terseness.

Besides these trivial examples, there are lots of cases where we need to have just the view of the container subset. For eg, while implementing string algorithms like pattern matching, you will always need to have a view of the substring of the text or whatever. The current available option is to call 'substr' method of string which will return you a copy of the string, now thats expensive. Otherwise, pass the start and end iterator which can be error prone.


Under the hood

The slice class adds a very thin wrapper around the container on which you want to create the slice. One thing it does currently is to derive from the base class i.e if you are creating a slice for a vector, then the slice<C> class is derived from vector. Here template parameter 'C' is the container itself.

Below example shows how you create a slice:

    std::vector<int> vec{1,2,3,4,5,6,7,8,9,10};

    // all elements
    auto vslice = make_slice(vec, 0, vec.size());
    assert(len(vslice) == 10);

    vslice = vslice(beg, 8); // slice of first 8 elements


1. 'make_slice' is a template function which creates a new slice for you.
2. 'operator()' is overloaded to provide the slicing functionality.
3. Two or more slices created by copy construction or by assignment shares the same container underneath since the slice just holds the reference to the container.
4. slice does not own the container. In the above case vector 'vec' is controlled by the user. If vec gets destroyed, no slice must be used after that.
5. 'len' is a global function for getting the length of the slice. Same as 'len' function in Go.

Source Code Location : https://github.com/arun11299/Slices-in-Cpp

The source is currently in a .cc file instead of a header (I am just too lazy sometimes). You can find few more examples on using slices in it.

Compilation : It should work just fine if you have enabled C++11. I have tested it on both Clang and g++ 4.8.


Sunday, 19 April 2015

Moving forward....

In the previous post, I tried my best explaining about 'move' semantics in C++11. In this post I am planning to cover up remaining things, namely:
1) Forwarding References
2) Reference Collapsing Rules
3) Forwarding Constructors
4) Type Limiting Forwarding Constructors
And as many examples as possible ! Also, all examples were compiled with g++ 4.8.2 and run on Ubuntu 14.02.

Since this post is a follow up on my previous post (the subject line does not indicate that), I would recommend to read through that before jumping here.

Link to previous post : Who moved my object ? No, not std::move!

Let's get started!!

Forwarding References

Now, since we are pretty much comfortable with R-Value references, lets go through some very simple examples and guess (it wouldn't be a guess if you know :) ) what would happen.

class Elf {
};

void take_elf(Elf&& elf) {  //..... (1)
    // do elf stuffs
}

template <typename T>
void templated_elf(T&& param) { // .. (6)
    // do elf stuffs 
}

int main() {
    Elf&& legolas = Elf();    // .... (2)  
    
    Elf&& dobby = legolas;    // .... (3)
    
    Elf rl_dobby = legolas;   // .... (4)

    take_elf(rl_dobby);     // .... (5)

    templated_elf(rl_dobby);// .... (7) 

    return 0;
}

Lets go through the code as per the numbering and find out issues as we go by them. Everything is being done with/on class Elf.

1. It is a function taking an r-value reference of type class Elf. Looks good.

2. Variable 'legolas' is an r-value reference and we are assigning it with an unnamed object or a temporary object of type class Elf. This is what the purpose of r-value reference is, i.e. binding with temporaries. So, all looks fine here.

[Important]
3. Here too, variable 'dobby' is an r-value reference, but in this case we are assigning it with 'legolas' instead of a temporary Elf object. The difference is that, a temporary variable is not an r-value reference . So, once a temporary is bound to an r-value reference for eg: 'legolas', it behaves just like an l-value from there on. That means, 'legolas' is an r-value reference at its point of definition at (2), but from there on, it behaves just like an l-value.
Thus, this statement would result in an compilation error (type mismatch), since we are trying to assign an l-value ('legolas') to an r-value reference which is 'dobby'.

4. If (3) is clear, this statement should appear as a regular assignment statement and there is nothing more to that. We are assigning 'legolas' to 'rl_dobby'. Since both are l-values here, there is no compilation error.

5. This is similar to (3). We are trying to call function 'take_elf' which expects an r-value reference as parameter with an l-value 'rl_dobby'. Same reasons mentioned for (3) holds true here as well.
So, this will result in compilation error (type mismatch). You would see the same error, if the call parameter is replaced to 'legolas'.

6. Welcome to 'Forwarding References'. You might now ask, what is the big difference ? It looks exactly like 'take_elf' except the fact that it is templated. Lets answer this in the next section.


Welcome to Forwarding References


So, your question was "what's the big difference? It's just templated", wasn't it ? Well, what makes it special is the template itself.

Had it been a regular template function, i.e. 'T' or 'T&' or 'T*' instead of 'T&&', it would have behaved just like its explicit type counterpart (mostly), except for the fact that the template version accepts all data types (the signature part).

But a template r-value reference or a forwarding reference (T&&) does not exhibit the same behavior as that of its explicit type counterpart for eg: 'take_elf'. The difference is that 'T&&' behaves like an r-value reference i.e binds with rvalues/ temporaries but they can also behave like an l-value !
This duality allows them to bind with both r-values and l-values.

Thus, statement (7) in the code is valid and does not result in compilation error like it did for (3). It is because of the dual nature of forwarding reference (T&&).

Besides this, they can also bind to const, volatile and both const-volatile objects making them 'greedy functions'. It is so greedy that we have a separate section on it.

We have already seen one such example of forwarding reference in my previous post, where a vector was being passed to a function 'do_work_on_thread' which used a forwarding reference. (Well, that example was slightly incorrect. There is an update beneath that section).

How to write a forwarding reference ?
Quoting from Scott Meyer's 'Effective Modern C++':
"""
For a reference to be universal, type deduction is necessary, but it's not sufficient. The form of the reference declaration must also be correct, and that form is quite constrained. It must be precisely "T&&" 
""" 
NOTE: Here, universal reference means forwarding reference. Initially, it was Scott Meyers who identified the need to have a different terminology for such references and he named it as 'universal' reference. Later, the standard committie standardized it as 'forwarding reference'.

Based upon the above, something like below is not a forwarding reference:

template <typename T>
void func(std::vector<T>&& arg) {...}

But this is a forwarding reference:
auto&& var = Test();


Reference Collapsing Rules

There are basically four rules associated with reference collapsing and is only applicable in case of forwarding references. These are a set of deduction rules which must be remembered while working with forwarding references.










The easiest way to remember is that, only when there are four '&', it collapses into an r-value reference, for all other cases it collapses into an l-value reference. :)

Below example depicts the first two rules:

#include <iostream>

template <typename T>
void func(T& val) {
    val += 10; // For the sake of simplicity,
               // hoping its always int :D
}

int main() {
    int a = 10; 
    int& ans = a;
    func(a);
    std::cout << a << " " << ans << std::endl; // prints 20 20

    int&& ans2 = std::move(a);
    func(a);
    std::cout << ans2 << std::endl; // prints 30

    return 0;
}


Below example depicts the remaining 2 rules which are more important.

#include <iostream>

template <typename T>
void func(T&& param) {
    param += 10; // Assuming its int
}

int main() {
    int a = 10; 

    func(a);
    std::cout << a << std::endl; // prints 20, Rule no 3

    func(std::move(a)) ; // Rule no 4
    return 0;
}


As you would have got it by now, it's because of these rules when an l-value is passed to a forwarding reference, it accepts it as a reference.

Now, you could ask, why these rules are required at all ? These rules are required for 'perfect forwarding' to work, which we will see in the next section.

Perfect Forwarding


Why is such a thing there in the first place ? Well, it is because of the dual nature of forwarding references which we had seen earlier. Due to that, basically two different types converged to become an l-value reference inside the function body. After that, there is no way (without std::forward and some template magic) to determine what was the exact type passed into the function.

Consider below example:
void do_work(??) { // What type of argument ?
}


template <typename T>
void wrapper(T&& args) {
    // do some work on argss
    do_work(args);
}

So, here you are. Inside function 'wrapper' when you call 'do_work', you want to copy 'args' if it was passed as l-value or pass it as r-value if it was passed as r-value. Without 'std::forward', you could have done some template magic (check previous blog post for the source) to get the same effect, but that is error prone and I am not even sure if it would be a practical solution.
Let's see how std::forward solves this issue.

std::forward

Like std::move, std::forward is also a function template that does nothing but casting. But unlike std::move which does an unconditional cast, std::forward does a conditional cast.

This is how the implementation of std::forward looks like in g++ 4.8.2 (Made it visually appealing).

template <typename T>
T&&  forward(typename std::remove_reference<T>::type& t) noexcept
{ 
    return static_cast<T&&>(t); 
}

template <typename T>
T&&  forward(typename std::remove_reference<T>::type&& t) noexcept
{   
      return static_cast<T&&>(t);
}

Basically, the first function is enough for std::forward to work and from my experimentation also, the second overload never got called. So not sure why the second overload is there. In our examples, we will consider std::forward as the first function only.

Now, lets get back to our previous example and try to solve it by using std::forward.

class Test {
};

void do_work(const Test& t) { 
    Test a(t);
    //.....
}

void do_work(Test&& t) {
    // .......
}


template <typename T>
void wrapper(T&& args) {
    // do some work on argss
    do_work(std::forward<T>(args));
}

We solved the problem by creating 2 overloads of the 'do_work' function. First one accepting the argument by reference and the second one accepting the argument as r-value reference.
It's the job of the std::forward to cast it to the correct type and thereby call the correct overload.

Let's see how that is done. Consider the case of an l-value first:
Test t;
wrapper(t);

// Inside wrapper std::forward is called with template
// type as T.
// Since an l-value was passed, due to reference collapsing rules
// std::forward$lt;T> would essentially be std::forward<Test>

//So std::forward would be instantiated like

Test& &&  forward(typename std::remove_reference<Test&>::type& t) noexcept
{ return static_cast<Test& &&>(t); }

// Applying reference collapsing rules on it
Test& forward(Test& t) noexcept
{ return static_cast<Test&>(t); }

So, as you see for the above case, 'std::forward' casts it to an l-value reference and thereby calling the first 'do_work' overload.

Lets see the same for an r-value reference:
Test t;
wrapper(std::move(t));

// Inside wrapper, since an r-value was passed, due to reference collapsing rules
// std::forward<T> would essentially be std::forward<Test&&>

// So std::forward would be instantiated like this
Test&& && forward(Test&& && t) noexcept {
    return static_cast<T&& &&>(t);
}

//Applying reference collapsing rules
Test&& forward(Test&& t) noexcept {
    return static_cast<T&&>(t);
}

As you can see, this time it correctly cast it to an r-value reference, thereby making it call the second overload of the 'do_work' function.
This is the reason why std::forward is called conditional cast.


With that we finish with the basics of forwarding references and std::forward. The thing to remember is that, move is called with r-value references and forward is called with forwarding references.

Where to go from here ?

Back to your life :)
Take a break. Once you are ready to face fresh challenges, go through below resources:
1) http://thbecker.net/articles/rvalue_references/section_01.html
2) Scott Meyers "Effective Modern C++". Some examples in this post are influenced by his explanation.
3) What we have covered are the basics. There are more to move semantics based on its usage. For eg: Move constructor and its fallacies.
4) Know about move only types like std::unique_ptr, std::thread etc and how to work with them.



Sunday, 12 April 2015

Who moved my object ? No, not std::move!

It's been quite a long time since I really wanted something to blog about. So, I thought why not write up something on the new features introduced in C++11 which I found difficult to grasp or come in terms with initially.
It was not the lambda expression or the auto type deduction or the new c++11 threading memory model, but something much easier (Yes, easy because I understand it now ;) ), the move semantics and everything related to it.
The intention of this post is to ease your way into understanding move semantics and its 'not- so-obvious' fallacies.


Temporaries reloaded!


Anyone who has been working with C++ for sometime knows what I want to say here. And you would be right, there is nothing new with the temporaries as such in the new standard. What has been added is a way by which creation of temporaries does not add overhead to the run-time performance of your c++ code (and I know you want it as fast as possible, don't you?)
Let us consider an example code:

void my_func(const std::string& name) {
    names_vec.push_back(name);
}

std::string name("Galadriel");
my_func(name);                    // Passing lvalue
my_func(std::string("Gandalf"));  // Passing temporary string object
my_func("Goku");                  // Passing string literal

This looks like a 'good enough' piece of code. Passing temporaries like this will work since its lifetime would be extended since it gets bound to the const object.
And when doing 'push_back' inside the function, 'name' will get copied for the first two cases, whereas for the third case (string literal), a temporary string object needs to be created before copying it inside the 'names_vec' container.
Huh! Was that the best we could do ? Yeah, kind of in C++98/C++03. Hell no! for C++11. We can do much better in C++11, thanks to move semantics.

Welcome to move semantics


With C++11, a new type for temporary variables was born or standardized. This is called as 'R-Value Reference' , represented as 'T&&' (where T is any built-in or user defined type).
These R-value reference types gets bound to the temporaries or to other R-value references.

void my_func(std::string&& name) {
    names_vec.push_back(name);
}

my_func(std::string("Vegeta"));
std::string lval("lvalue");
my_func(lval);                // Compile error! my_func cannot accept lvalue

You see, how the temporary string object got accepted by our new function signature but got rejected at compile time for the lvalue! What I have shown you here is one way by which R-value reference type accepts parameters i.e as temporaries.

Now, the question is, how would I make 'my_func' accept my lvalue? Here is where 'std::move' comes into picture.

What does std::move do ? 



A hell lot of stuff you might be thinking, but no! All it does is a casting operation! See it for yourselves.
Below is the implementation of std::move in g++ 4.8.2 (Cleaned up a bit for easier understanding):

  template <typename T>
  typename std::remove_reference<T>::type&&
    move(T&& t) 
    { return static_cast<typename std::remove_reference<T>::type&&>(t); }

NOTE: 'std::remove_reference' is a type trait which as the name suggests provides the actual type passed in but without the reference. This is required because of the 'reference-collapsing' rule which we would be discussing later, but for the current context, it can be ignored.

If you ignore the 'remove_reference' type trait, the function template boils down to an unconditional cast to an R-value reference! That means, 'std::move' does not 'move' anything, to move or not is actually decided by the compiler. Doing an 'std::move' is just an request to the compiler to do move optimization.

So, I repeat the question, what would do to make lvalue to be accepted by 'my_func' ? Yes, you move the lvalue which would cast it to an r-value.

Where is the optimization ?



This is the meaty part of the discussion. In simple terms, what move means is to point to a different memory location where the required object is placed or allocated. So, instead of copying the object to a new memory location, just point it to its current location. This is obviously a lot more efficient than copying!
This can be shown easily by the below diagram:



As you can see from the diagram, moving vector 'vl' does not require copying the entire vector. 
But, the same is the case if we had passed it by reference or const reference, what is so special here ? To answer this question, lets look at another slightly bigger example (Read comments in code to understand):

#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>

template<typename T>
void do_work_on_thread(T&& ip_vec) {
    std::for_each(ip_vec.begin(), ip_vec.end(), 
                    [](int v) { std::cout << v << std::endl; } );
    return;
}

void accept_vec(std::vector<int> vec) {       // First complete copy
    std::cout << "Accept vec non optimized" << std::endl;
    // do some work on the input vector
    // .....

    // Asynchronously work on the vector by feeding 
    // it to a thread.
    do_work_on_thread(vec);                   // Second complete copy
    return;
}

void accept_vec2(std::vector<int>&& vec) {    // No copy, vector just moved
    std::cout << "Accept vec optimized" << std::endl;
    // do some work on the input vector
    // .....

    // Asynchronously work on the vector by feeding
    // it to a thread.
    do_work_on_thread(std::move(vec));        // No copy, vector just moved
    return;
}

int main() {
    std::vector<int> v = {1,2,3,4,5,6,7,8,9};
    accept_vec(v);              // Old style
    accept_vec2(std::move(v));  // New move optimized style
    return 0;
}

Being a bit more smart, one copy can be avoided in the 'old style', but still one copy is required for the life time guarantees of the vector. Whereas with move, no copy is required at all!

UPDATE:
In the comments section, Pavel raised a question on where the second copy is happening in case of 'accept_vec' function. And he is right on target, there is no second copy happening there. The vector gets passed as a reference (Because of reference collapsing rules which we will probably discuss in next post).
So, the problem has become just more sever for me. For the 'accept_vec' case, I need to pass the vector by value to 'do_work_on_thread' since the vector is going to be handled asynchronously and I need to guarantee its life time and also at the same time, it should not pass by value if I am moving it.

Well, it seems like it can be achieved with some template magic.Here it goes:

#include <iostream>
#include <utility>
#include <type_traits>

class Test {
public:
    Test() {
        std::cout << "Cons" << std::endl;
    }   
    Test(const Test& other) {
        std::cout << "Copy Cons" << std::endl;
    }   
    Test(Test&& other) {
        std::cout << "Move cons" << std::endl;
    }   
    void operator= (const Test& other) {
        std::cout << "Assignment op" << std::endl;
    }   
    void operator= (Test&& other) {
        std::cout << "Move assignment op" << std::endl;
    }
};

template <typename T, bool U>
struct detail {
        // Constructor copies it to arg1
        detail(const T& param): arg1(param) { 
                std::cout << "Generic detail" << std::endl; 
        }
        typename std::remove_reference<T>::type arg1;
}; 

// Template specialization for detail when T is not a reference
// Here I am just assuming it to be an r-value reference, whereas
// in real scenario one should handle for other types as well.
template <typename T>
struct detail<T, false>  {
        // Constructor just moves the param to arg1
        detail(T& param): arg1(std::move(param)) { 
                std::cout << "Specialized detail" << std::endl; 
        }
        typename std::remove_reference<T>::type arg1;
};

/* Assume that this function
* will process 'arg' asynchronously.
* That means, fwd_ref must own the arg and its
* life time must not be controlled by any other frame
*/
template <typename T>
void fwd_ref(T&& arg) {
    std::cout << "Called fwd_ref" << std::endl;
    std::cout << std::is_reference<T>::value << std::endl;
    detail<T, std::is_reference<T>::value> d(arg);
    return;
}

int main() {
    Test t;
    fwd_ref(std::move(t)); // pass as R-value reference
    fwd_ref(t);            // Pass by value
    return 0;
}


So, in the above code, the magic happens in the 'detail' struct, which copies the constructor argument when it receives a reference, and move the argument when it is 'not-a' reference (which we consider as move for simplicity.
One thing to remember here is that there are other simpler ways to achieve the same with some design change. The only thing that made it complicated is the use of 'forwarding reference' assuming it to be used along with thread.


Move Constructors and Move Assignment


We all know that, if a class is managing a memory resource, it is important to provide the class with a copy constructor, assignment operator and destructor. Support for move operation in user defined classes is done via 'move constructors' and 'move assignment'. So, the 'Big three' becomes 'Big five' in C++11.
Lets look at an example right away(Would not be using smart pointers, apologies for that) [Compiled with g++ 4.8.2]:

#include <iostream>
#include <utility>
                  
class MemoryMgr {
public:
    MemoryMgr(size_t size):mp_block(new uint8_t[size]()),
                           m_blk_size(size) {
    }
        
    MemoryMgr(const MemoryMgr& other) {
        std::cout << "Copy cons" << std::endl;
        if (this == &other) return;
        mp_block = new uint8_t[other.m_blk_size]();
        m_blk_size = other.m_blk_size;
        std::copy(other.mp_block, other.mp_block + other.m_blk_size,
                  mp_block);
    }
/*
    MemoryMgr& operator=(MemoryMgr other) {
        std::cout << "Ass op" << std::endl;
        std::swap(other.mp_block, mp_block);
        std::swap(other.m_blk_size, m_blk_size);

        return *this;
    }   
*/ 
   MemoryMgr(MemoryMgr&& other) {
        std::cout << "Move copy cons" << std::endl;
        mp_block = other.mp_block;
        m_blk_size = other.m_blk_size;
        
        other.mp_block = nullptr;
        other.m_blk_size = 0;
    }

    MemoryMgr& operator=(MemoryMgr&& other) {
        std::cout << "Move assignment op" <<  std::endl;
        if (this == &other) return *this;

        delete[] mp_block;
        mp_block = other.mp_block;
        m_blk_size = other.m_blk_size;

        other.mp_block = nullptr;
        other.m_blk_size = 0;
    }


    virtual ~MemoryMgr() noexcept {
        delete[] mp_block;
        m_blk_size = 0;
    }

private:
    uint8_t* mp_block = nullptr;
    size_t m_blk_size = 0;
};


int main() {
    MemoryMgr obj1(100);
    MemoryMgr obj2(std::move(obj1)); // Move constructor will be called
                                     // NOTE: Once moved, obj1 should not be used again inside main

    MemoryMgr obj3(40);
    obj3 = std::move(obj2);          // Move assignment will be called. Much efficient than regular assignment op
                                     // NOTE: Once moved, obj2 should not be used again inside main

    return 0;
}

One can go through the example and check how the implementation is done for move constructor and move assignment operator. It should be very much clear that, the move operations are much more efficient and faster than the regular copy constructor and assignment operator.

NOTE: I have commented out the assignment operator, since the compiler was finding it ambiguous with the mover assignment operator. This is because, we are accepting the argument by value, which can accept r-value references as well. This can be corrected by making the assignment operator take input parameter by const reference. I leave this to the reader as an exercise :)


Not everything is green !


I would be very skeptic if everything looked so easy and straight-forward in C++. So, lets get down to the quirkiness.

1. Move is more efficient for head based containers/objects
Though all containers in the standard library support move operation, but not for all containers moving would be as cheap as for showed for std::vector. For eg, take the case for std::array, in which the container elements are directly inside std::array object.
Therefore, for this case, the move operation needs to be done for all the elements inside the array. If there is no move constructor provided for the object held by the array, then the time taken is as good as for the copy operation.

2. Once moved, the object state is valid but in unspecified state
Consider the below example:
    std::vector v1 = {1, 2, 3, 4};
    assert( v1.size() == 4 );            // Assertion is valid

    std::vector v2 = std::move(v1);
    assert( v2.size() == 4 );            // Assertion is valid
  
    assert( v1.size() == 4 );            // Assertion is INVALID, size() for v1 may or may not be 4

    v1 = v2;                             // v1 can be assigned to new vector


As can be seen from the example, once moved, it is incorrect to rely on the state of the moved object, for eg: size(), empty(), etc.
The moved object can be assigned with other similar objects sice that does not require any precondition checks.

3. Move constructor and Move assignment operators are not generated by default in many cases
Unlike copy constructor and assignment operator, compiler does not always (*) generate default move constructor and default assignment operator when not provided by the user.

NOTE(*): Not for all cases default constructor or default copy constructor or default assignment operator are implicitly created by the compiler.

a. Default move operations are generated only if user has not explicitly provided implementation for copy constructor or assignment operator or destructor.
b. Default move operations are not generated if the user has provided an implementation for copy constructor or assignment operator or destructor. In this case compiler thinks that something different  or extra needs to be done for moving the resource(s) managed by the class.

4. Do not move objects in return statement
Consider below example:
// Return by Copy version
Object create() {
    Object obj;
    return obj;
}


// Move Version
Object create() {
    Object obj;
    return std::move(obj);
}

Which one do you think would be more efficient, copy version or the move version ? The heading would have given it away anyways :) But, for the sake of explanation, its the copy version that would be more efficient. This is because of NRVO (Named return value optimization), which every decent compiler does (mostly with optimization flags turned on). If RVO/NRVO kicks in, the compiler can completely elide copy and move construction.

With NRVO, the object would be created directly at the destination, requiring no copy at all. This is called as 'copy ellision'.

With the move version, compiler does not do NRVO/RVO, but one has to depend upon the move constructor of Object.

But, NRVO/RVO is not applicable at all times, for eg: the return statements are provided under if-else statements! In this wouldn't it be better to move rather than depend on compiler ?? Cool down, as per the standard, if copy-ellision is not applicable, the 'std::move' is implicitly applied. :)

UPDATE (From Scott Meyers Modern effective C++) : NRVO/RVO optimization requires that we return the local object from the function. But, this is not the case if we return the moved object. The moved object is basically a reference to the object, not the object itself.

Code demonstrating the same [Compiled with g++ 4.8.2]:
#include <iostream>
#include <array>

class Object {
public:
    Object() {
        std::cout << "Cons" << std::endl;
    }   
    Object(const Object& other) {
        std::cout << "Copy Cons" << std::endl;
    }   
    Object(Object&& other) {
        std::cout << "Move cons" << std::endl;
    }   
    void operator= (const Object& other) {
        std::cout << "Assignment op" << std::endl;
    }   
    void operator= (Object&& other) {
        std::cout << "Move assignment op" << std::endl;
    }   
};

std::array<Object, 2> get_array_no_move() {
    std::cout << "Enter get_array" << std::endl;
    std::array<Object, 2> arr;
    std::cout << "Array init" << std::endl;
    arr[0] = Object();
    arr[1] = Object();
    std::cout << "Leaving" << std::endl;
    
    return arr;
}


std::array<Object, 2> get_array() {
    std::cout << "Enter get_array" << std::endl;
    std::array<Object, 2> arr;
    std::cout << "Array init" << std::endl;
    arr[0] = Object();
    arr[1] = Object();
    std::cout << "Leaving" << std::endl;
    
    return std::move(arr);
}

int main() {
    std::array<Object, 2> res = get_array();
    std::cout << "Got res" << std::endl;

    std::array<Object, 2> res2 = get_array_no_move();
    return 0;
}

If you look at the output (after compiling with -O2 optimization flag), it would be clearly visible that get_array_no_move does not have any move constructors called while returning the array object, but the move constructor gets called in case of get_array function. This is because for get_array_no_move the copy and move constructor got elided because of NRVO.

5. Move does not work with const objects
Obviously, how can a constant object move!! Well, the technical reason is that, doing a move may or may not modify the source object, which is against the requirement of const objects.
For this reason, the below example will compile, but you cannot reap the benefits of move:
class Test {
public:
    Test(const std::string& name): m_name(std::move(name)){
    }
private:
    std::string m_name;
};


Phew! So far so good. I was planning to continue with Forwarding references and  Perfect Forwarding in this same post, but now I think it would be better to have them in a separate post else someone would sue me for causing mental depression.

Will update the post with the link to the next post. Till then, wait-for-it.

Update : Part two of the series  

Sunday, 22 February 2015

Fun with Template Meta-programming, enable_if_all

It is true that sometimes ignorance is bliss...sometimes. In my case ignorance or to be more specific, lack of curiosity over this weekend to "just try it out once" lead me to do a lot of crazy stuff with template meta-programming.

What I wanted
While working on my side project work, I came across with the need of having a class with forwarding constructor. Now, people familiar with C++11 would know how greedy a forwarding constructor can be, it's so greedy that it starts taking up the role of copy constructor (for non const object) until we limit it by SFINAE (Substitution Failure Is Not An Error). 

One can lookup here to know what I am talking about.

So, back to my problem. I am sitting here with a need to have a forwarding constructor taking variable template parameters or variadic templates, but also have my copy constructor work for me without any issues. The known solution for such cases is to use some kind of SFINAE or to be more specific use 'std::enable_if'. But, here I am working with variadic templates instead of just known number of template parameters. At this point, I just made one heck of an 'assumption' that 'std::enable_if' won't work with variadic templates and immediately (out of too much excitement) sat down to implement my own generic 'enable_if_all' type trait. Oh, boy! that was embarassing !

What was the big idea ?
The idea was to create a type trait that would take any other type_trait structures (C++11 has got so many of them, check it out here) which accepts 1 or 2 template parameter in general along with bunch variable number of other types on which the type_trait would be applied to get the final result, which is either 'true' or 'false', just like 'std::enable_if'.

But, after a lot of attempts I figured out many things that won't work with template meta-programming. Finally I had to settle for a very naive solution and at the same time figured out that 'std::enable_if' also works with variadic templates and also with type_traits requiring more that 1 template parameter (for eg. std::is_constructible, std::is_same).

In the process, I discovered a missing feature that if present would have been so beautiful and powerful. Currently, there are two ways by which you can pass a template class as a template parameter:

1. Along with the type, i.e as a complete type.

template <typename T>
class Test {
};

template <class ClsT>
class Composer {
};

int main() {
    Composer<Test<int>> cmp;
    return 0;
}

2. Without the type information i.e as template template parameter


template <typename T>
class Test {
};

template <template <typename> class ClsT, typename T>
class Composer {
private:
    ClsT<T> cmp_;
};

int main() {
    Composer<Test, int> cmp;
    return 0;
}

Now, what would have been more beautiful is if we had something like template type 'explosion'. Something like below:

template <typename A, typename B> class Test {};

template <template <typename T1, typename T2> class ClsT>
class Composer {
};


In this case, we would be able to make use of template parameters T1 and T2 as well. But, currently c++ does not allow that. Had it worked, I would be still ignorant about 'std::enable_if'.

What I have ?
Nothing much to be proud showing off, but some important lessons learnt (which I may forget over a period of time :)) related to template meta-programming. It is surely a different language within C++. It might be harsh to untrained eyes, but a real beauty to someone who understands it. Hope it won't be killed by 'auto' in future c++ standards.

Here is my version of 'enable_if_all'. Note that, a lot of things are still missing in it.

#include <type_traits>

template <typename Type>
struct SType {
    typedef Type type;
};

template <template <typename...> class ValidatnFn, typename... Types>
struct enable_if_all;

template <template <typename> class ValidatnFn, typename LastT>
struct enable_if_all<ValidatnFn, LastT> {
    static bool const value = ValidatnFn<LastT>::value;
};

// This is for type_trait checks taking in only single template parameter
template <template <typename> class ValidatnFn, typename FirstT, typename... RestT>
struct enable_if_all<ValidatnFn, FirstT, RestT...> {
    static bool const value = ValidatnFn<FirstT>::value & enable_if_all<ValidatnFn, RestT...>::value ;
};

template <template <typename, typename> class ValidatnFn, typename FirstT, typename LastT>
struct enable_if_all<ValidatnFn, FirstT, LastT> {
    static bool const value = ValidatnFn<typename FirstT::type, LastT>::value;
};

// This is for type_trait checks taking in 2 template parameters
template <template <typename, typename> class ValidatnFn, typename FirstT, typename SecT, typename... RestT>
struct enable_if_all<ValidatnFn, FirstT, SecT, RestT...> {
    static bool const value = ValidatnFn<typename FirstT::type, SecT>::value & enable_if_all<ValidatnFn, FirstT, RestT...>::value ;
};

If you are eyes are itching, please pay a visit to doctor!  :)