私はコンストラクタをうまく特殊化することができます:
template < typename TType >
class Field
{
public:
Field( const Msg& )
: _type( TType() )
{ }
protected:
TType _type;
};
template < >
Field < double >::Field( const Msg& msg )
: _type( msg.extractDouble() )
{
}
template < >
Field < int >::Field( const Msg& msg )
: _type( msg.extractInt() )
{
}
ただし、次のような型以外の引数を取るテンプレートでも同じことを行う必要があります。
template < const char* pszName, typename TType >
class Field
{
public:
Field( const Msg& )
: _type( TType() )
{ }
static void setup( const Descriptor& d ) { // called once to setup _nIndex based on Descriptor and pszName
static int index() { return _nIndex; }
protected:
TType _type; // This class can only be sizeof TType in size
static int _index;
};
template < >
Field < ??, ?? >::Field( const Msg& msg ) // This doesn't compile
: _type( msg.extractDouble( index() ) )
{
}
template < >
Field < ??, ?? >::Field( const Msg& msg ) // This doesn't compile
: _type( msg.extractInt( index() ) )
{
}
これを行うためのトリックはありますか?実行時に setup() 中に const char 名を渡すことができると思います。しかし、オブジェクト自体が支援なしで知っていれば、それは素晴らしいことです。