2012/07/04

String chain using Typelist

久々ですがまたまたまた C++ Typelistネタ。

最近本当につくづく思うのですが、プログラミングにおいて Compositeパターンだとか、再帰的な 構造というのが、物事をシンプルにするのにすごく役立つということを感じます。

教科書的な Compositeパターンとしては、Compositeクラスなるものが あるインターフェースを継承した オブジェクトをコンテナに保有していて、そのアクションをコンテナオブジェクトに委譲するというものだったり しますが、このアイデアを「型」すなわちクラスまで持っていくと、より強力な構築概念になるのではないかと思います。

TypelistはこのCompositeパターンを構成するのに非常に役立つ道具と言えると思います。ここで文字列チェーンクラスを考えてみましょう。
template <typename T, typename TL>
struct StringChain;

// Chain starter implementation

template <NullType, NullType>
struct StringChain
{
    template <typename T>
    StringChain< T, Typelist<NullType, NullType> > operator()(const T& obj) const
    {
        return StringChain<T, Typelist<NullType, NullType> >(obj, *this);
    }

    ...
};
いきなり特殊化されたクラスを書き始めましたが、まずこの StringChainクラスはテンプレートの第一引数にある型、第二引数には、Typelistでエンコードされた型を取ります。そしてこの特殊化されたクラスは、Chainスタータと言って、文字列チェーンを作成開始するための特別なクラスとなります。 operator() 関数を使って、このクラスを成長させて行く訳です。

template <typename T, typename TL>
struct StringChain
{
    StringChain(const T& t, const StringChain& tl)
    : head(t), tail(tl)
    {
    }

    template < typename X >
    StringChain< X, Typelist< T, TL > > operator()(const T& obj)
    {
        return StringChain< X, Typelist< T, TL > > (obj, *this);
    }

    std::string str() const
    {
        std::string ret_str;
        ret_str.resize(getSize());
        size_t offset = 0;
        tail_.appendString(&ret_str[0], offset);
        appendString(&ret_str[offset], offset);
        return ret_str;
    }

    size_t getSize() const
    {
        return tail.getSize() + doGetSize(head);
    }

    void appendString(char* str_ptr,  size_t& offset) const
    {
        tail.appendString(str_ptr, offset);
        offset += doAppendString(str_ptr + offset, head);
        return;
    }
};

ここで doAppendString, doGetSize は StringChainの head要素に格納されているオブジェクトに対して 文字列を書き込む関数と文字列長を返却する関数です。 StringChainクラスにて扱う型に対してあらかじめ これらの関数を準備しておきます。
下記にサンプル実装をポストしました。
http://ideone.com/Ubmtd


It's quite long time since I posted C++ programming matter last time. This is again and again C++ Typelist.

Recently, I often come to think that so-called Composite pattern or some sort of recursive pattern / structure should be the key to simplify the structure in the programming.

According to some authoritative book or textbook kind of stuffs, what is explained as Composite pattern will be typically as follows. So-called Composite class which accommodates inherited class objects in its container or something like that, and then it delegates the very action to those objects. I would rather say that if we could successfully take this idea on to the level of type i.e. user-defined type (class), we can get more powerful construct.

And also I can say that Typelist can help to construct this pattern when it comes to applying Composite pattern into the type. As an example, let's consider the String chain class below.
template <typename T, typename TL>
struct StringChain;

// Chain starter implementation

template <NullType, NullType>
struct StringChain
{
    template <typename T>
    StringChain< T, Typelist<NullType, NullType> > operator()(const T& obj) const
    {
        return StringChain<T, Typelist<NullType, NullType> >(obj, *this);
    }

    ...
};
Although this is the very specialized class template implementation, StringChain class here will take 2 template paramters which takes first argument as conventional type and second argument as typelist encoded type. And this specialized class template is called as 'Chain starter', which will trigger the string chain object creation. By making use of operator() function, we are going to make the string chain grow.

template <typename T, typename TL>
struct StringChain
{
    StringChain(const T& t, const StringChain& tl)
    : head(t), tail(tl)
    {
    }

    template < typename X >
    StringChain< X, Typelist< T, TL > > operator()(const T& obj)
    {
        return StringChain< X, Typelist< T, TL > > (obj, *this);
    }

    std::string str() const
    {
        std::string ret_str;
        ret_str.resize(getSize());
        size_t offset = 0;
        tail_.appendString(&ret_str[0], offset);
        appendString(&ret_str[offset], offset);
        return ret_str;
    }

    size_t getSize() const
    {
        return tail.getSize() + doGetSize(head);
    }

    void appendString(char* str_ptr,  size_t& offset) const
    {
        tail.appendString(str_ptr, offset);
        offset += doAppendString(str_ptr + offset, head);
        return;
    }
};

Here, doAppendString and doGestSize function is the function to write head element to string buffer and size retrieval. We are supposed to prepare for appropriate overload functions towards types we are going to use with StringChain class in advance.
As for some sort of concrete code snippet, please take a look at the following. http://ideone.com/Ubmtd


Reference
Advanced C++ Metaprogramming - by Davide Di Gennaro

2012/06/21

Come back on court - Kei Nishikori

錦織選手がようやく怪我から復帰したようです。とにかく怪我には気をつけて今シーズンを 頑張ってほしいです。

早速 ウインブルドンやロンドンオリンピックが控えています。ウインブルドンは第19シード ですね。頑張れ!



It was reported that Japanese professional tennis player Kei Nishikori came back on court. Hope he continues to play this season without any further injuries.

Great thing that we may be able to see is that he should be shortly joining the exciting tournaments such as Wimbledon , London Olympic games etc.. As for the Wimbledon Championship, he is No.19 seeded. Anyway I believe that he can make it!

2012/03/14

Observer pattern using template and Typelist

またまた Typelistの話題。これまでのTypelistの用法を参考にして、Design Patternのうち
有用な Observerパターンを考えてみましょう。

まずは Observerクラスから。これに関しては任意の型のイベントを受け取るといった想定
で、下記のようなシンプルなテンプレートクラスにします。


#ifndef OBSERVER_H_
#define OBSERVER_H_

#include "typelist.h"

template <typename T>
class Observer
{
public:
    virtual void update(const T& event) = 0;
    virtual ~Observer() {}
};

#endif // OBSERVER_H_

このObserverクラスに対する通知を担う Subjectクラスですが、ここでTypelistを使用
してみます。


#ifndef SUBJECT_H_
#define SUBJECT_H_

#include <vector>
#include "typelist.h"
#include "observer.h"

template <typename TL>
class Subject;

template <typename T, typename U>
class Subject< Typelist<T, U> > : public Subject<U>
{
    typedef std::vector<Observer<T>*> Vector;
public:
    Subject() : observers_()
    {
    }

    ~Subject()
    {
    }

    using Subject<U>::notify;
    void notify(const T& event)
    {
        typename Vector::iterator it = observers_.begin(), end_it = observers_.end();
        for (; it != end_it; ++it) {
            (*it)->update(event);
        }
    }

    using Subject<U>::attach;
    void attach(Observer<T>* observer_ptr)
    {
        observers_.push_back(observer_ptr);
    }

    using Subject<U>::detach;
    void detach(Observer<T>* observer_ptr)
    {
        typename Vector::iterator it = observers_.begin(), end_it = observers_.end();

        for (; it != end_it; ++it) {
            if ((*it) == observer_ptr) {
                break;
            }
        }

        if (it != end_it) {
            observers_.erase(it);
        }
    }

private:
    Vector observers_;
};

template <>
class Subject<NullType>
{
public:
    void notify(const NullType& /* no use */)
    {
    }

    void attach(const NullType& /* no use */)
    {
    }

    void detach(const NullType& /* no use */)
    {
    }
};

#endif // SUBJECT_H_

このSubjectクラスはテンプレートパラメータとしてTypelistを受け取り、Typelist要素の型
に対して attach, detach, notify操作を支援します。クライアントコードにおいては、
Subjectクラスオブジェクトをメンバーとして保有して、detach, attachを委譲するような
メソッドを定義してやれば良い感じになります。

EventTypeListという型でイベントの型集合のTypelistがあるとすると、attach, detachの
委譲メソッドは下記のような感じになります。

#ifndef CONCRETE_SUBJECT_H
#define CONCRETE_SUBJECT_H

#include "subject.h"
#include "event_type_list.h"

class ConcreteSubject
{
public:
    ConcreteSubject();

    template <typename T>
    void attach(Observer<T>* observer)
    {
        typedef typename TypelistOf<EventTypeList, T>::Result TL;
        subject_.Subject<TL>::attach(observer);
    }

    template <typename T>
    void detach(Observer<T>* observer)
    {
        typedef typename TypelistOf<EventTypeList, T>::Result TL;
        subject_.Subject<TL>::detach(observer);
    }

    void action1();
    void action2();

private:
    Subject<EventTypeList> subject_;
};

ここで TypelistOfは以前に紹介した Typelistの部分集合を取り出す操作になります。



Again, I would like to take a look at Typelist. Making use of what has been adopted
until now, I would like to come up with Observer pattern which is quite useful among
various Design Patterns.

First, let's take a look at Observer class. Since we would like to handle various event
types, we are supposed to make the Observer class as parameterized class
(template class) as follows.

#ifndef OBSERVER_H_
#define OBSERVER_H_

#include "typelist.h"

template <typename T>
class Observer
{
public:
    virtual void update(const T& event) = 0;
    virtual ~Observer() {}
};

#endif // OBSERVER_H_

Secondly, we are going to build up Subject class by making use of Typelist as
follows.

#ifndef SUBJECT_H_
#define SUBJECT_H_

#include <vector>
#include "typelist.h"
#include "observer.h"

template <typename TL>
class Subject;

template <typename T, typename U>
class Subject< Typelist<T, U> > : public Subject<U>
{
    typedef std::vector<Observer<T>*> Vector;
public:
    Subject() : observers_()
    {
    }

    ~Subject()
    {
    }

    using Subject<U>::notify;
    void notify(const T& event)
    {
        typename Vector::iterator it = observers_.begin(), end_it = observers_.end();
        for (; it != end_it; ++it) {
            (*it)->update(event);
        }
    }

    using Subject<U>::attach;
    void attach(Observer<T>* observer_ptr)
    {
        observers_.push_back(observer_ptr);
    }

    using Subject<U>::detach;
    void detach(Observer<T>* observer_ptr)
    {
        typename Vector::iterator it = observers_.begin(), end_it = observers_.end();

        for (; it != end_it; ++it) {
            if ((*it) == observer_ptr) {
                break;
            }
        }

        if (it != end_it) {
            observers_.erase(it);
        }
    }

private:
    Vector observers_;
};

template <>
class Subject<NullType>
{
public:
    void notify(const NullType& /* no use */)
    {
    }

    void attach(const NullType& /* no use */)
    {
    }

    void detach(const NullType& /* no use */)
    {
    }
};

#endif // SUBJECT_H_

This parameterized Subject class would intake Typelist as template parameter
and then support attach, detach and notify operations towards respective
Typelist element types. In client code, we are supposed to composite the Subject
class object and then write some appropriate attach and detach method as
delegation.

Assuming that EventTypeList is the Typelist for various event types we are going to
support here, delegation methods for attach and detach will be like the following.

#ifndef CONCRETE_SUBJECT_H
#define CONCRETE_SUBJECT_H

#include "subject.h"
#include "event_type_list.h"

class ConcreteSubject
{
public:
    ConcreteSubject();

    template <typename T>
    void attach(Observer<T>* observer)
    {
        typedef typename TypelistOf<EventTypeList, T>::Result TL;
        subject_.Subject<TL>::attach(observer);
    }

    template <typename T>
    void detach(Observer<T>* observer)
    {
        typedef typename TypelistOf<EventTypeList, T>::Result TL;
        subject_.Subject<TL>::detach(observer);
    }

    void action1();
    void action2();

private:
    Subject<EventTypeList> subject_;
};

Here, TypelistOf operation is what was introduced the other day.

2012/03/13

Biz trip to NY

業務上でしたが、先週初めてNew Yorkに行ってきました。

当然仕事なので、New York観光という訳にはなかなか行きませんでしたが、少しは観光する
ことが出来ました。

一つはスポーツや音楽のイベントの聖地とも言える「ザ・ガーデン」こと Madison Square
Gardenにてカレッジバスケットボールの観戦と、ブロードウェイ(正確にはオフ・ブロード
ウェイ)のミュージカルを見ることが出来ました。

カレッジバスケットボールでは Big East Conferenceと呼ばれるカンファレンスから
Louisville vs Setonhallと University of South Florida vs Villanova の試合を観戦。

個人的には 1試合目の Louisvilleの内容が良かった。効果的なゾーンディフェンスで相手の
切り込みを封じていたように見えたし、PGの選手のシュート、パスそれから身体能力の
高さに驚かされました。この選手、ちょっと調べてみたところそれなりに注目されている
選手のようで、下記のような記事もあったり、YouTube映像なども投稿されていました。
ぜひとも将来はNBA入りして頑張ってもらいたいですね。

Draft NBA Express - Peyton Siva

もう一つのブロードウェイは、英語があまり判らないだろうということで、台詞が理解でき
なくても楽しめそうなものとして Million Dollar Quartet というのを鑑賞しました。これは
1950年代のある日に収録されたジャムセッションを再現するような形で綴られた、古き良き
ロックンロールのミュージカルです。Surf, Garage, Rockabilly好きの私としては
たまらない内容でとても良かったです。

Official site - Million Dollar Quartet



I had a chance to travel to New York for the first time last week, although it was a biz
trip.

Although the purpose of the trip was, of course, business, I could have spent some
time for some sightseeing, visiting NYC.

Firstly, I visited so-called "The Garden" Madison Square Garden - holy place for
sports and music where I could watch college basketball. And also I watched a(n)
(Off-)Broadway musical.

In college basketball games, I watched the following 2 games from Big East
Conference - Louisville vs Setonhall and University of South Florida vs Villanova.

I enjoyed the first game (Louisville vs Setonhall) very much. Louisville's zone
defense seemed to me quite effective towards the opponent and then effectively
prevent them from penetrate into the inner area. And also the PG's was quite good
for shots, passes and his physical performance. According to google, it seems that
he is rather famous among basketball fans.


Draft NBA Express - Peyton Siva

I hope that he can turn pro - NBA in future and can even succeed in his career.

As for the musical in the broadway, since it was quite possible that I could not
understand the exact dialog in the play, I chose Million Dollar Quartet where I
expected that I could enjoy even if I could not understand the story. The motif
of this musical came from a certain famous rock & roll jam session in 1950s,
which should have definitely attracted me, since I'm a big fan of such kind of
music like Surf, Garage and Rockabilly etc..



2012/02/29

Don't leave any broken window unattended

タイトルは「割れ窓」を放っておくな です。

これに関して、自分自身を振り返ってみるとなかなか実践できません。物事は放っておくと
エントロピー増大の法則で無秩序が拡大していくことを、改めて肝に銘じて置かないとと、
最近感じました。

社会学の世界では「割れ窓理論」は必ずしも認められていないようですが、このメタファー
はいろんなレベルで当てはまることが多いのではないでしょうか?




When it comes to the situation around me on the subjected matter, I must admit
that it's quite difficult for me to behave like this. We have to keep in our mind that
any kind of things will follow the second law of thermodynamics (law of entropy
increase). And we should continue to strive not to have any broken window.

It seems that so-called broken windows theory is not always appreciated in the
world of sociology. However, I think that this should be applicable in various
situations.



Reference : Extract from the book - Pragmatic Programmer
                   Broken Windows Theory (Wikipedia)

2012/02/24

Typelist exercise - TypelistOf, TypelistAt operation

またまたC++ネタ、しかもまたTypelistです。

Typelistから Typelistの部分集合を得る操作をやってみましょう。ネーミングが適切
かどうか判りませんが、 先頭に配置したい要素を指定する TypelistOfオペレーションと
N回下る操作の TypelistAtを考えてみます。


template <typename TL, typename V>
struct TypelistOf;

template <typename T, typename U, typename V>
struct TypelistOf< Typelist<T, U> >
{
    typedef typename TypelistOf<U, V>::Result Result;
};

template <typename T, typename V>
struct TypelistOf< Typelist<V, T>, V >
{
    typedef Typelist<V, T> Result;
};



次は N番目のTypelistを得る TypelistAt操作です。
template <typename TL, int N>
struct TypelistAt;

template <typename T, typename U>
struct TypelistAt<Typelist<T, U>, 0>
{
    typedef Typelist<T, U> Result;
};

template <typename T, typename U, int N>
struct TypelistAt<Typelist<T, U>, N>
{
    typedef typename Typelist<U, N - 1>::Result Result;
};



こういったTypelist操作を持っていると単一継承階層を作るのに非常に便利だと思います。
例えばTypelistAt操作を使って 下記のような感じでTupleを構成できます。

template <typename TL>
struct Tuple;

template <typename T, typename U>
struct Tuple< Typelist<T, U> > : public Tuple<U>
{
    T value;

    typedef Typelist<T, U> ThisType;

    template <int N>
    typename TypeAt<ThisType, N>::Result& getValue()
    {
        typedef Tuple<typename TypelistAt<ThisType, N>::Result> ThatType;
        return this->ThatType::value;
    }
};


Modern C++ Designで紹介されている Tupleよりずっとシンプルだと思います。
またこのアイデアは Advanced C++ Metaprogrammingで紹介されている pop_front操作をより
汎化させたものとも言えます。同様の実装が本書では Agglomerate objectとして紹介されています。





Again, I'm going to take a look at another C++ matter and also it is regarding Typelist.

Let's try to manipulate Typelist to derive 'partial' Typelist. Although I'm not really sure
the naming adopted here is appropriate, TypelistOf is the operation to derive the partial Typelist
whose first element type is the requested type. Another one, TypelistAt is the simple operation
to derive N-th Typlist.

The TypelistOf operation will be something like the following.

template <typename TL, typename V>
struct TypelistOf;

template <typename T, typename U, typename V>
struct TypelistOf< Typelist<T, U> >
{
    typedef typename TypelistOf<U, V>::Result Result;
};

template <typename T, typename V>
struct TypelistOf< Typelist<V, T>, V >
{
    typedef Typelist<V, T> Result;
};



On the other hand, TypelistAt operation should be something like this.

template <typename TL, int N>
struct TypelistAt;

template <typename T, typename U>
struct TypelistAt<Typelist<T, U>, 0>
{
    typedef Typelist<T, U> Result;
};

template <typename T, typename U, int N>
struct TypelistAt<Typelist<T, U>, N>
{
    typedef typename Typelist<U, N - 1>::Result Result;
};



I think this type of Typelist operation will be useful when you want to construct single inheritance
hierarchy. For example, when you use TyplistAt operation, you will be able to easily realize so-called 'Tuple'
as follows.

template <typename TL>
struct Tuple;

template <typename T, typename U>
struct Tuple< Typelist<T, U> > : public Tuple<U>
{
    T value;

    typedef Typelist<T, U> ThisType;

    template <int N>
    typename TypeAt<ThisType, N>::Result& getValue()
    {
        typedef Tuple<typename TypelistAt<ThisType, N>::Result> ThatType;
        return this->ThatType::value;
    }
};


I wonder the above implementation should be much simpler and easy to understand than what is
introduced in Modern C++ Design.

And also, this idea will be some more generic version of 'pop_front' operation which is explained in Advanced
C++ Metaprogramming. A similar implementation is also introduced in this book as 'agglomerate object'.

2012/02/23

Very very small tips on STL std::pair

STL std::pair< >についての小ネタ

ちょっと備忘録的なものですが、std::pairって 下記のように算術演算子が overloadされているんですね。知らなかった。

#include <utility>
class TestClass
{
    // ... some implementation here
};

TestClass test1, test2;

std::pair<TestClass, int> obj1(test1, 2), obj2(test2, 3);

bool ret = (obj1 == obj2);  // TestClassに bool operator==(const TestClass& rhs) const などが定義されていれば可能

ret = (obj1 < obj2);  // TestClassに bool operator<(const TestClass& rhs) constなどが定義されていれば可能


テンプレートのインスタンス化は利用される時まで遅らせるという仕組みがうまく利用されている実装ですね。




This is very very small tips in terms of std::pair< > .

I didn't know that std::pair< > implementation also overloads arithmetic operators until now.

#include <utility>
class TestClass
{
    // ... some implementation here
};

TestClass test1, test2;

std::pair<TestClass, int> obj1(test1, 2), obj2(test2, 3);

bool ret = (obj1 == obj2);  // possible if TestClass define e.g. bool operator==(const TestClass& rhs) const

ret = (obj1 < obj2);  // possible if TestClass defines e.g. bool operator<(const TestClass& rhs) const


Now we can see that lazy evaluation of the template instantiation surely makes for.



Reference: C++ Reference - pair

2012/02/18

Another implementation of TypeAt as Typelist operation

現在 Advanced C++ Metaprogrammingを読書中。最初に目次を確認した時には、
Typelistについては扱っていないのか?と思いましたが、それなりにページが割かれて
いるようです。

書く人が違うと実装も様々ですね。 LokiのTypelistでは TypeAt操作は下記のような感じ
です。

template <class TList, unsigned int index>
struct TypeAt;

template <class Head, class Tail>
struct TypeAt<Typelist<Head, Tail>, 0>
{
    typedef Head Result;
};

template <class Head, class Tail, unsigned int i>
struct TypeAt<Typelist<Head, Tail>, i>
{
    typedef typename TypeAt<Tail, i - 1>::Result Result;
};

これと同様なものが Advanced C++ Metaprogrammingでは次のような実装が紹介されて
います。

template <class TList, unsigned int index>
struct TypeAt;

template <class T, class U, unsigned int index>
struct TypeAt<Typelist<T, U>, index> : public TypeAt<U, index - 1>
{
};

template <class T, class U>
struct TypeAt<Typelist<T, U>, 0>
{
    typedef T Result;
};

template metaprogrammingではこのように継承を使うと場合によっては簡潔になる
ケースがあるんですね(ほとんど変わっていないという見方もありますが)。しかしながら、
採用しているコンパイラオプションによっては warningが出てしまうので、そういう点も
加味して実装を決定しましょう。




I'm now reading the book Advanced C++ Metaprogramming. When I first took a look
at the Table Of Contents, I didn't find that there is a section or chapter which talks
about Typelist. But there is.

I now realized that Typelist implementation should be varied. According to the
Loki implementation, TypeAt manipulation is defined something like below.

template <class TList, unsigned int index>
struct TypeAt;

template <class Head, class Tail>
struct TypeAt<Typelist<Head, Tail>, 0>
{
    typedef Head Result;
};

template <class Head, class Tail, unsigned int i>
struct TypeAt<Typelist<Head, Tail>, i>
{
    typedef typename TypeAt<Tail, i - 1>::Result Result;
};

On the other hand, the same TypeAt manipulation in Advanced C++ Metaprogramming
is defined something like this.

template <class TList, unsigned int index>
struct TypeAt;

template <class T, class U, unsigned int index>
struct TypeAt<Typelist<T, U>, index> : public TypeAt<U, index - 1>
{
};

template <class T, class U>
struct TypeAt<Typelist<T, U>, 0>
{
    typedef T Result;
};

where we can see that using derivation or inheritance may contribute to being
simpler implementation in some sense. However, we may need to take more care
in case that we are going to use derivation / inheritance, since a certain compiler
option may give some warning.. (e.g. in case that we set up -Weffc++ option etc. in
GCC[g++]).



2012/02/12

Typelist exercise - forEach operation toward types



C++に関係する書籍で、中級者・上級者プログラマーに大きな影響を与えたものとしては
やはり Modern C++ Design ではないでしょうか?私がこの本に出会ったのは非常に
遅かったですが、その内容には目から鱗の連続だったと記憶しています。

その中でも最もインパクトがあったのはやはり Typelistでしょう。templateの特殊化などを
駆使して型の操作を行う様は、それまでに全く想像しなかったものでした。

ここではこのTypelist操作の練習とし、型に対するfor_eachを実現してみます。Typelistの
型に対する操作を走査します。

ここでファンクタは、Typelistの各要素型に対する操作を行う訳ですから、templateの operator()となる訳です。

for_eachを体現するテンプレートクラス forEach_tを書いてみます。

template <class TL, class Functor>
struct forEach_t
{
    forEach_t(Functor& functor)
    {
        typedef typename TL::Head THead;
        functor.template operator()<THead>();
        forEach_t<typename TL::Tail, Functor> nested(functor);
        (void) nested;
        return;
    }
};

template <class T, class Functor>
struct forEach_t< Typelist<T, NullType>, Functor>
{
    forEach_t(Functor& functor)
    {
        functor.template operator()<T>();
        return;
    }
};

ここで、Functorクラスは与えた引数で推論できるようにテンプレート関数を導入します。

template <class TL, class Functor>
inline void forEach(const Functor& functor)
{
    Functor func(functor);
    forEach_t<TL, Functor> temp(func);
    return;
}

では、実際に使ってみましょう。ファンクタはあまり凝らずに typeid()で操作対象の型情報を 出力するだけにしています。

#include <iostream>
#include <typeinfo>
#include "typelist.h" // forEach, foeEach_t is also defined here

class TestFunctor
{
public:
    TestFunctor()
    {
    }

    template <typename T>
    void operator()()
    {
        std::cout << "Test Functor executed - typeid [" << typeid(T).name() << " ] " << std::endl;
    }
};

struct TestClass1 {};
struct TestClass2 {};
struct TestClass3 {};
struct TestClass4 {};

typedef MakeTypelist<TestClass1, TestClass2, TestClass3, TestClass4>::Result TL;

int main(int argc, char* argv[])
{
    (void) argc; (void) argv;

    forEach<TL>(TestFunctor());
}

実行結果は下記のような感じになりました。

Test Functor executed - typeid [10TestClass1 ] 
Test Functor executed - typeid [10TestClass2 ] 
Test Functor executed - typeid [10TestClass3 ] 
Test Functor executed - typeid [10TestClass4 ] 

きちんと for_each操作されているようですね。




Among various books on C++, I wonder that Modern C++ Design is one of the books
that impose pretty big impact on intermediate / advanced C++ programmer.
Although the time I met this book was quite late, I surely remember that various
things covered in this book were all quite impressed me very much. If I'm supposed
to raise the most impressive technique, it must be 'Typelist' as you may relate to.
Making use of template specialization etc., a sort of type manipulation using Typelist
was something I could not imagine until then, indeed...

Here, I will show you some exercise on how to do for_each operation towards
various types in Typelist

Since functor being used in this for_each operation will be handling Type, operator()
member function shall be template member function.

Please take a look at the following forEach_t class which has the very for_each
operation towards Types.

template <class TL, class Functor>
struct forEach_t
{
    forEach_t(Functor& functor)
    {
        typedef typename TL::Head THead;
        functor.template operator()<THead>();
        forEach_t<typename TL::Tail, Functor> nested(functor);
        (void) nested;
        return;
    }
};

template <class T, class Functor>
struct forEach_t< Typelist<T, NullType>, Functor>
{
    forEach_t(Functor& functor)
    {
        functor.template operator()<T>();
        return;
    }
};

here, we're going to introduce inline template function to deduce Functor class type.

template <class TL, class Functor>
inline void forEach(const Functor& functor)
{
    Functor func(functor);
    forEach_t<TL, Functor> temp(func);
    return;
}

See how it works by writing some simple client code. Here, I've used typeid() to do some operation towards various types.

#include <iostream>
#include <typeinfo>
#include "typelist.h" // forEach, foeEach_t is also defined here

class TestFunctor
{
public:
    TestFunctor()
    {
    }

    template <typename T>
    void operator()()
    {
        std::cout << "Test Functor executed - typeid [" << typeid(T).name() << " ] " << std::endl;
    }
};

struct TestClass1 {};
struct TestClass2 {};
struct TestClass3 {};
struct TestClass4 {};

typedef MakeTypelist<TestClass1, TestClass2, TestClass3, TestClass4>::Result TL;

int main(int argc, char* argv[])
{
    (void) argc; (void) argv;

    forEach<TL>(TestFunctor());
}

We can get the following result. Now we can see that we could make it.

Test Functor executed - typeid [10TestClass1 ] 
Test Functor executed - typeid [10TestClass2 ] 
Test Functor executed - typeid [10TestClass3 ] 
Test Functor executed - typeid [10TestClass4 ] 


2012/02/07

Taxicab number

Wikipediaをサーフィンしていたら、個人的に面白いものを見つけました。

Wikipediaに数多くの「数」の説明があることに気づきました。

例えば「1」
「1000」なんかも説明がある・・・
「10000」も・・・
一体いくつまで説明があるんだろうといった感じです。

1から10000まで連続した数すべてに説明があるかどうかは調べきれていませんが、
例えば数学者などにとっては、数というのはそれぐらい重要というか、注目に値する
ことなんですね。

こんなことに辿り着いたのは、個人的に興味のあった数学者ラマヌジャンのラマヌジャン数
っていくつだったっけ?というのを調べようとして辿り着いたのでした。

ラマヌジャン数は正確にはハーディ=ラマヌジャン数もしくはタクシー数というんですね。
タクシー数として知られるこのエピソードが非常に興味深いですね。

ラマヌジャンは数々の公式や定理を発見したことで知られていますが、一つ面白かったのが
入れ子の平方根 に関するこの式です。


この無限にネストした平方根の答えは 3だそうです。簡単な説明が ここに書いてあります
が、自分では良く分かりませんでした。

天才の考えていることは良く分かりませんが、こういうことを調べたりするとちょっと頭
の体操になりますね。



While net-surfing in Wikipedia, I found something which is interesting to me
personally.

Wikipedia has number of pages about 'numbers'... that's it.

For example, there is a page for '1'.
'1000' and also, you can find the page for '10000' as well...

I haven't precisely checked whether every single number has its own page from 1 to
10000. However, I wonder the point is that those numbers really matter for
someone and attract a lot of attentions towards e.g. mathematicians etc..

The reason why I came to find such things comes from my personal interest in
the former famous mathematician Srinivasa Ramanujan and my short investigation
about which is so-called Ramanujan number is.

It seems that what I refer to as Ramanujan number is called as Ramanujan-Hardy
number or Taxicab number... Anyway, the story about why this is called as Taxicab
number is quite interesting.

Ramanujan is very famous for his discovery of a lot of mathematical theorems and
formulas. The following was one of them which is regarding 'nested radicals' and is
really interesting to me.


According to the short explanation here, the answer to this nested radical is '3'...
I could not clearly relate to this answer in the end...

Anyway, coming to think of this kind of difficult things, which is not totally related
to our daily life, is sometimes helpful for our brain exercises, isn't it?


2012/02/06

Tiny Template Library (TTL) ... seems to be helpful

ネットサーフィンやってたら、下記のようなオープンソースソフトを発見。テンプレート
メタプログラミングを理解するには非常に良さそうです。

Tiny Template Library

Overviewによると Boostの軽量化版を目指してということなので、Boostのソースを
根気よく読むまではいかないけど、そのエッセンスを勉強したいというような場合には
役立つのではないでしょうか?

とりあえず variantあたりの実装を確認してみようかな?と思います。



While net-surfing, I found the following open source software which seems to be
very helpful to study / understand so-called template metaprogramming.

Tiny Template Library

According to Overview chapter in the site, it seems that it aims to be a lightweight
alternative of some of the Boost components, it seems to make for studying some
of the essence of what should be inclusive in Boost implementation rather than
taking a close look at the Boost source code.

I'm now inclined to take a look at how the 'variant' implementation is like there.



Reference: Tiny Template Library : variant (article from CodeProject)

2012/02/01

Go Kei !! (2)

今週の ATP tour rankingによると錦織選手はなんと男子シングルス世界ランキング20位に
躍進。もちろん日本人男子として過去最高位ということですごいっ!

今年は出だしも良く、いろんな大会でシード権も獲得できそうなので、今後の活躍に期待
しましょう。




According to ATP tour ranking this week, Japanese professional tennis player
Kei Nishikori jumped up to the 20th in Men's singles ranking, which is, of course,
the highest ranking reached by Japanese professional tennis players ever. That's
really great!!

As he made some good start, we can expect that he will be seeded in some
tournaments, which should help him. So in this sense, we can expect his successful
season in 2012. Go Kei!!


2012/01/31

[Book review] Advanced C++ Programming Styles and Idioms

Advanced C++ Programming Styles and Idioms    C++ プログラミングの筋と定石



今回は私がC++の世界にはまった最初の書籍について紹介します。

C++で最も有名な書籍といえば Scott Meyers氏のEffective C++ だと思いますが、
初めてEffective C++を読んだ時には、文章ばかりであまりピンと来ませんでした。
そもそも自分の C++及びオブジェクト指向に対する不勉強のためだったと思います。

そういう状況で見つけたのが本書籍でした。US Amazonのレビューで見つけて、邦訳本が
あることを知らなかったので、洋書で購入して読みました。遠回りしてしまった感もある
にはあるのですが、実際に邦訳本を立ち読みしてみましたが、分かりにくいというか
頭にしっくり入ってこない部分もあったので、時間は掛かったけど洋書で読んで正解だった
かなという風にも思っています。

驚くことにこの本の出版日はなんと 1991年だそうです。もう20年以上も前のこと。著者
の James O. Coplienは 「C++の設計と進化」によると C++の最初のユーザー(正確には
Cfront)だったということですが、その時点でここまで深堀りできているという点に驚き
です。

当然古い出版のため、新しい言語仕様に対する記載(例えば templateや namespaceなど)に
関する説明はなかったり、一部現行仕様と相容れない記述もあるかと思いますが、非常に
参考になるテクニックが記載されています。

しかしながら、この本の多くの技巧のアプローチは、C++の強力なタイプシステムを
いくらか柔軟にして利用するために、Polymorphismを多用したものとなっています。
現在のオブジェクト指向プログラミングでは、なんでもかんでも共通のベースクラスから
派生させるようなスタイルはあまり採用しないと思います。紹介されているテクニック
そのものはプロダクトコードに用いずに、そのテクニックのエッセンスを自身の
プログラミングに利用するというのが良いかと思います。

この書籍では「イディオム」という形で、テクニックやコンセプトに名前を付け、その
コンパクトに名付けられた「イディオム」で、プログラマーが共通認識を持って
ソフトウェアの生産性を上げることを狙っていたものと思われます。この流れが、その後
の「デザインパターン」といったムーブメントへ繋がっていったんでしょうね。

Scott Meyersの More Effective C++では参考文献として、本書は LSD本として紹介
されています。洋書のカバーの色合いと、紹介されている技巧から LSDとは・・・なるほど
言い得て妙だなと感じました。




This time let me introduce a book on C++ programming language which took me into
the deep world of C++.

I wonder the world-most-famous book on C++ should be "Effective C++" by Scott
Meyers. However, when I first read the book, I had a feeling that I didn't fully
understand what the book tries to address very well. I must admit that it was due to
my lack of well-understanding of the language as well as sort of lengthy text in that
book.

In such situation, I found this book. Since I didn't know that Japanese translation was
also available at that moment, I bought English version by checking US Amazon
review. When I realized that Japanese version was available, it is true that I felt like I
went a long way around. However, when I browsed the Japanese version in a
bookstore, I found some portion seems not so intuitive. Now I wonder it deserves
reading English version even if it takes me some more time to complete it.

I was surprised that the publication date was in 1991 - more than 20 years before.
The author James O. Coplien was said to be the first user of C++ (to be precise,
Cfront) according to the book 'Design and Evolution of C++'. Anyway, I'm quite
surprised that he has deeply investigated into that much even in this early stage of
C++.

As this is quite old book, there are some of missing portions in terms of rather
new language specification such as template, namespace etc.. and also you may
find something which is not aligned with the current C++ specification. But it is also
true that it contains a lot of techniques which are very helpful.

However, many of the techniques introduced in this book are sort of one-sided.
I mean they often adopt polymorphism, attempting to lessen the benefit of C++
strong type system to get some more flexibility. I don't think that present way of
doing object-oriented programming is like creating inheritance hierarchy among
almost all the objects from a single commonal base class. It would be better not to
make use of the code technique shown in this book into production code as it is.
Instead, we can make better use of those essences into our daily programming.

In this book, it names various techniques and concepts in the form of 'idioms'.
I believe that those idioms are aimed to be widely shared among programmers
in order to get common understanding via such compact names, which helps to
improve our software productivity and quality etc.. and I also believe this idea must
have had something to do with the later 'design pattern' movement.

In famous book 'More Effective C++' by Scott Meyers, this book was introduced as
'LSD' book. Now I can relate to, from the coloring adapted by the book cover and
its various techniques introduced in this book.


2012/01/30

Google-code-prettify

今後いろいろとソースコードを貼付けたりして記事を書いてみたいので、ソースコード表示
用のCSSである、google-code-prettify を導入してみる。

参考というか、そのままこちら のサイトを利用させて貰いました。

で、試しにサンプルコードを書いてみる。


#include <memory>

class TestClassImpl;

class TestClass
{
pubilc:
    void someMethod();

private:
    std::auto_ptr<TestClassImpl> pimpl_;
};

きちんと Code prettifyされていそうですね。




Since I would like to post various articles on programming matters, I'm going to
introduce some CSS which improves some readability for source code by making
use of google-code-prettify .

I referred to the this site (in Japanese) while introducing the CSS. That's really
helpful indeed.

The following is my first trial to see if the source code can be in some organized
way.

#include <memory>

class TestClassImpl;

class TestClass
{
pubilc:
    void someMethod();

private:
    std::auto_ptr<TestClassImpl> pimpl_;
};

Now I can see it is quite code-prettified, isn't it?

2012/01/19

Go Kei!!

錦織選手がやってくれました。フルセットの末、3回戦進出。現在全豪オープン真っ最中。
WOWOWなどには加入していないので、試合をみる手段はないですが、日本人選手として
頑張って欲しいですね。



Japanese professional tennis player Kei Nishikori advanced to 3rd round in men's singles in Australian Open Championship tournament. Although I have no chance
or way to watch his game live, I've backed up him indeed. Go Kei!! You can make it!


2012/01/09

Good paper and good pen are better than any other GTD stuffs??



時々自分の仕事の仕方などを見直そうと思って、LifeHack的なアイデアを探したりします。
そして、いくつかを試して軌道に乗ったりもするんですが、結果としてはいつも「長続き」
しないということになってしまいます。結局LifeHackになっていない・・・

結局アナログなやり方が性にあっているのか?現在はこれらを愛用しています。

一つ目は、PilotのFrixion Ball 0.5mmというペンです。知っている方も多いかと思います
が、ペンでありながら熱でインクを消すことができる優れものです。書き味も自分好み。

一度車内にこのペンを置きっぱなしにして、中のインクが完全に消えたことがありましたが、
原理を正しく理解して注意して使うとかなり便利です。

もう一つは、ペンを使って書く側のノートです。前はMoleskinを使っていましたが(これは
これで良かったのですが)、今は RHODIAの Meeting Bookというを使っています。表紙が
比較的固くてずーっと持ち歩いていても中の紙がヘタれないのと、ページの構成が非常に
使い安く気に入っています。

普段はこれを持ち歩いて、電車通勤時に立ったままで、ちょっと思いついたことや ToDo
事項をこれにメモして使っています。個人主観かも知れませんが、このFrixionとRHODIAの
相性が抜群で書きやすい。

いつかは Evernoteとか使いこなそうと思っていますが、現在はアナログ手法で進めます。





I often come to think that I should find some more better way to do getting things
done by making use of some useful LifeHack tools etc., and then try to look for
such good stuffs. Some of them would attract me to use. However, as is often
the case, the result is that after a while, I would gradually become not to use them...
It's not like LifeHacking at all in the end...

The current conclusion seems to be that some more 'analog' equipment suites me.

The first item is a pen, Pentel Frixion Ball. In the top(?) of the pen, it equips with
rubber ball. You can erase the ink by using that rubber (with heat) in spite that it is
a pen! It's quite useful. And also its writing is very well for me.

However, when you use this pen, you are supposed to be careful. I once kept this
pen in my car for a while, which totally disappered all the ink in the pen... The ink
inclusive in the pen is quite weak at heat... So you would need to understand the
rationale when using it.

The other one is paper - a notebook. I used 'Moleskin' before. But now I realized that
RHODIA classical Meeting Book is quite confortable for me to keep on writing. Its
cover pages are appropriately hard and can protect inner pages well. And page
layout adopted by this notebook is really good.

I usually take these stuffs while commuting (by train) and then whenever anything
comes up to my mind, I'm supposed to take notes in the book by using the pen.
Although this is my personal thought, these two items go together very well.

I'm also thinking to use some cool tool like Evernote in the near future. But I'm rather
content with such analog stuffs so far.



2012/01/07

2 books about recent brain research

単純な脳、複雑な「私」- 池谷 裕二

ゆらぐ脳 - 池谷 裕二

今回は池谷 裕二さんという脳科学者が著した2つの本を挙げます。

1冊目は筆者の母校(高校)の生徒達に、現在の脳科学の最先端トピックや人が自然と不思議
に思うであろう様々な話題で行われる講義の実況中継のような形で進められます。

よく陥る様々な「脳のクセ」や「意識と無意識」についての話題などどのページを捲っても
知的好奇心をかき立てるような話題の連続です。

個人的に興味深かったのが、「アルファ波をモニタすることさえできれば、アルファ波を
抑制させることが出来る。必要なものはフィードバック。」といったところ。自分の生活
や業務に当てはめてみても、メタなレベルでこの例が示唆することは重要ではないかと
思います。

自分はソフトウェア開発をやっていますが、アジャイル・リーン原則といったものは「迅速
なフィードバックを得、改善を絶えず行っていく」姿勢や実践にあります。これも極論
すれば人間の脳に必要なフィードバックを得て、人間が物事をコントロールしていくことに
つながるんですかね・・・。そのフィードバックを実現するためにも計測は必要ということ
でしょうか。

2冊目は2者の対談という形式で綴られた、科学者のあるべき姿を追求するような内容に
なっています。といっても脳科学の最新の話題なども取り扱われて、困難な話題がすんなり
と読者に入っていくような思慮が為されていると思います。

あらゆる物事を「考える」とき、脳を使ってそれは実践される。脳科学では、その「考える」
対象が脳であり、その中での発見が、自身の「考える」姿勢、思想・哲学感にも影響を
与える・・・なんだか再帰的で、複雑そうに思えてくるものもあります。

また仮説 - 検証型の研究に対する疑問というか批判についての下りは昔に読んだ福岡伸一氏
の本の中にも似たような記述があったような気がします(野口 英世の研究についてのくだり
だったかと思います)。

私は研究者ではないですが、業務・生活の中で下すべき決断について良く仮説-検証型の手順
を踏んで物事を進めることが多いので、また別の視点を入れてみるようなことを考えて
みようかという気にさせてくれました。




This time let me introduce 2 books written by Japanese brain researcher Yuji Ikegaya
(Gaya), titles of which are something like the following

  • The brain - the simple, Myself - the complicated
  • Continuously fluctuating brain


The first book features his teaching at his old high school, where he was once
welcomed as a guest. And its way of proceeding with stories is like as if it were live
coverage.

It features various interesting topics related to brain such as what kind of 
interesting and/or funny habit the brain is having, how consciousness and
unconsciousness are working mutually etc.. All of them inspired my intellectual
curiosity quite a lot.

What is quite interesting to me is what he mentions in this book as follows.
"If we can continuously monitor alpha wave, then we can take all the control of
our alpha wave. All the things we would need here is just a feedback."

I now believe, if we can apply this rationale to a higher-order level, what he meant
here should be applicable in various situations no matter what it be our job, our daily
life etc..

I'm now engaged in software development and then strive to apply Agile and Lean
principles there. These principles should be obviously based on the attitude that we
pursue "prompt feedback and continuous improvement". Now I wonder this attitude
should well fit into human mental model, just like the brain gets such feedbacks and
then make use of those feedbacks to take control of things…. In order to get such
feedback, it seems that continuous measurement should be the key to any success,
isn't it?

The second book is in the form of dialog between the author and an interviewer and
features what should be required for scientists. However, of course, it also features
various hot topics about recent brain researches and definitely should attract 
readers in this way.

When human tries to think something, its action/bahavior will be performed by
making use of the brain. In brain research, its object to 'think' should be, of course, 
the brain. Whatever discovered in the research, it will have a quite good deal of
impact on his way of thinking afterwards, his thought and even his philosophy...
This cycle is a sort of recursive, makes me complicated in a way… but quite 
interesting.

And also this book raises some question or even criticism towards most
conventional approach to solve any problem - making hypothesis and verification if
the hypothesis is true. I wonder his point is that if we always take the approach, 
something quite important may be overlooked. Although I'm not a researcher, I must
admit that I often tend to adopt such approach (hypothesis and verification), I now 
have a feeling that I would need have some other view on this matter.


Book about C++ template metaprogramming

   Advanced C++ Metaprogramming - by Davide Di Gennaro

C++のテンプレート、その中でもTMP(Template Metaprogramming)に関する書籍って
本当に少ないですね。日本語の書籍となるとまた限られるので、思い切って洋書を購入。
昨日到着しました。

US AmazonのBook reivewで、本の体裁が悪い(スタイルなどが醜いのと、Errataも多数)というのが気になりました、テーマとして貴重だと思ったので購入したものです。

まだ読み始めた最中ですが、読み終わって何かえるものがあったらこのブログに掲載しよう
と思います。

----------

   Advanced C++ Metaprogramming - by Davide Di Gennaro

As you may know, there are quite few books available which talk about C++ template metaprogramming. The situation should be much worse in case of such books available in Japanese... So I've decided and purchased this English book. (It should be a sort of tall order for me to complete this book...)

According to US Amazon book review, there are a few bad comments on its styles and numerous errata which once hesitated me to buy it. However, I've bought the one since the theme this book is handling is quite valuable, I thought.

I haven't yet completed to read this book since it's just arrived. I'll later on post what I  could find very valuable in this book in some day...


Googlemock - how to handle the case multiple overloaded member methods are present

Googlemock使ってますか?私は使い始めて間もないですが、非常に便利です。単体テスト
を実施したい場合にネックとなるのが、他のクラスなどへの依存性ですが、これを
Googlemockを使用してモックオブジェクトを差し込んで、テストの実施およびテストの
網羅度を向上させることができます。

下記のように同じ名前のメンバ関数を持つようなクラスのモック化ではまってしまったので
メモしておきます。

class SomeClass
{
public:
    ...
    virtual void someMethod(int i);
    virtual void someMethod(std::string& str);
    ...
};



このようなクラスをMock化して使用する場合には、EXPECT_CALL()マクロ使用において、
Matcherの記述において引数の型を明示する必要があるため ::testing::Matcher<> というの
を記載する必要があります。

class MockSomeClass : public SomeClass
{
public:
    ...
    MOCK_METHOD1(someMethod, void(int));
    MOCK_METHOD1(someMethod, void(std::string&));
};
....

// Test code
MockSomeClass mock;
...
// In case that we would expect latter method is invoked here.
EXPECT_CALL(mock, someMethod(::testing::Matcher<std::string&>(::testing::_)))
...
// instead of
// EXPECT_CALL(mock, someMethod, ::testing::_);
// ...

Are you using Googlemock? Although I've just started playing with it, I found it is
quite useful. Whenever trying to perform unit testing, what can be some obstacle to
achieve unit testing would be dependency on other classes etc.. However, we will be
able to eliminate such dependency to outside by introducing mock object instead of
the actual class object. This is the way that we can achieve unit testing and even
improve test coverage toward developed software. The other day I had some hard
time to handle the following case for a while in handling some polymorphic class
where the same name of member methods are defined.

class SomeClass
{
public:
    ...
    virtual void someMethod(int i);
    virtual void someMethod(std::string& str);
    ...
};

In case of trying to mock such class, we would need to have a bit special treatment
when using EXPECT_CALL() macro. When you write down matcher portion, you are
supposed to use ::testing::Matcher<> to specify the argument type which is being
expected here. Otherwise, EXPECT_CALL() can be treated as ambiguous...

class MockSomeClass : public SomeClass
{
public:
    ...
    MOCK_METHOD1(someMethod, void(int));
    MOCK_METHOD1(someMethod, void(std::string&));
};
....

// Test code
MockSomeClass mock;
...
// In case that we would expect latter method is invoked here.
EXPECT_CALL(mock, someMethod(::testing::Matcher<std::string&>(::testing::_)))
...
// instead of
// EXPECT_CALL(mock, someMethod, ::testing::_);
// ...