Boost.TypeErasure を使ってみた

と、言うことで以前から気になっていた Boost.TypeErasure をちょっとつついてみました。

[ソース]

#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/builtin.hpp>
#include <boost/type_erasure/operators.hpp>
#include <boost/mpl/vector.hpp>
#include <iostream>


struct X{
    X() : value(0){}

    int value;

    int
    operator ++(){
        return ++++value;
    }
};

std::ostream&
operator <<(std::ostream& os, X const& x){
    return os << x.value;
}


int
main(){
    namespace t = boost::type_erasure;
    namespace m = boost::mpl;
    
    // 格納するオブジェクトのコンセプト
    typedef m::vector<
        t::copy_constructible<>,
        t::typeid_<>,
        t::incrementable<>,
        t::ostreamable<>
    > requirements;
    
    {
        t::any<requirements> x(10);
        ++x;
        ++x;
        std::cout << x << std::endl;    // 12
    }

    {
        X tmp;
        t::any<requirements> x(tmp);
        ++x;
        ++x;
        std::cout << x << std::endl;    // 4
    }

    return 0;
}

[出力]

12
4

こんな感じで、格納するオブジェクトのコンセプトを指定して使用します。
Boost.Variant よりも抽象的で Boost.Any よりも明示的、って感じですかね。
思ったよりも使い勝手がよさそうです。


あ、あと constexpr の初期化回りでエラーが出ていて C++11 だとコンパイルエラーになりました/(^o^)\