final クラス

Java のマルチスレッドなコードを読んでいると、不変性を保つために final が使用されていることが多い。

public final class Immutable
{
    private final String field1;
    private final String field2;
    ...
}

final メンバは const で代用できるとして、final クラスを C++ ではどうやればいいんだろうと思って調べてみると、boost に nonderivable というのがあるようだ。

namespace boost
{

    namespace nonderivable_ // Protection from unintended ADL
    {
        /*
         * Helper class
         */
        class nonderivable_helper
        {
            friend class nonderivable;
            
            private:
                virtual void uniqueness() = 0; // This will hide uniqueness in derived classes
            
            protected:
                virtual ~nonderivable_helper() {} // included just to avoid some warnings
                
                nonderivable_helper() {}
        };

        /*
         * "nonderivable" derives from the protected virtual base
         * class nonderivable_helper. By overriding the pure virtual
         * method uniqueness, it ensures that no class can derive
         * twice from nonderivable, since it will cause a compilation
         * error, since there would be more final overriders for the
         * uniqueness method.
         */
        class nonderivable : protected virtual nonderivable_helper
        {
            private:
                virtual void uniqueness() {}
        };
    }
    
    typedef nonderivable_::nonderivable nonderivable;
}

#define BOOST_NON_DERIVABLE private ::boost::nonderivable
class Immutable : BOOST_NON_DERIVABLE
{
private:
    const std::string field1;
    const std::string field2;
    ...
};

む、でもこれを継承すると仮想テーブルを持ったクラスになるのか……微妙かも。
しかもバージョン 1.34.1 には入っていないみたいだし……お蔵入りしたのかな。


やっぱりドキュメンテーションで回避するしかないかorz