C++Builderのライブテンプレート

ライブテンプレートが手軽で、かつ、かなり便利なのでライブテンプレートの作り方C++Builder2009のライブテンプレートを使うを参考に作ってみた。作ったのは、アクセサの自動生成。

アクセサとプロパティの宣言部分(accessor_decl.xml)

<?xml version="1.0" encoding="utf-8" ?>
<codetemplate   xmlns="http://schemas.borland.com/Delphi/2005/codetemplates"
                version="1.0.0">
    <template name="accessor_decl" invoke="manual">
        <description>
            アクセサ&プロパティ宣言
        </description>
        <author>
            A7M
        </author>
        <point name="Variable">
            <text>
                Variable
            </text>
            <hint>
                変数名
            </hint>
        </point>
        <point name="T">
            <text>
                T
            </text>
            <hint>
                型名
            </hint>
        </point>
        <code language="C"><![CDATA[
$T$  get$Variable$(void) const;
void set$Variable$(const $T$& val);
__property $T$ $Variable$ = {read = get$Variable$, write=set$Variable$};
]]>
        </code>
    </template>
</codetemplate>


アクセサの実装部分(accessor_impl.xml)

<?xml version="1.0" encoding="utf-8" ?>
<codetemplate   xmlns="http://schemas.borland.com/Delphi/2005/codetemplates"
                version="1.0.0">
    <template name="accessor_impl" invoke="manual">
        <description>
            アクセサ実装
        </description>
        <author>
            A7M
        </author>
        <point name="Class">
            <text>
                Class
            </text>
            <hint>
                クラス名
            </hint>
        </point>
        <point name="Variable">
            <text>
                Variable
            </text>
            <hint>
                変数名
            </hint>
        </point>
        <point name="T">
            <text>
                T
            </text>
            <hint>
                型名
            </hint>
        </point>
        <code language="C"><![CDATA[$T$  $Class$::get$Variable$(void) const
{
    return m_$Variable$;
}

void $Class$::set$Variable$(const $T$& val)
{
    m_$Variable$ = val;
}]]>
        </code>
    </template>
</codetemplate>

これらのファイルを$(BDSUSERDIR)\code_templatesにUTF-8で保存する。コードエディタ上でCtrl+Jを入力すると一覧が表示されるので、適当なテンプレートを選択。必要な項目を入力すると、その中身を自動的に補完してくれる。

C++でアクセサを使用することについては議論があるかもしれないけど、アクセサで値を随時チェックすることによって不正な値が入るのを防止出来るので、個人的には便利だと思う。アクセサが冗長であればプロパティを使えばいいし。プロパティ自体、C++の言語仕様には無いけど、Boost.Propertiesで無理矢理実装するみたいだし、Visual C++拡張機能で使用できるので、シンタックスシュガーとしていいんでないの?