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!!