[英]how to specialize a template constructor
我能夠專門研究構造函數:
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名稱。 但是,如果對象本身知道而沒有幫助,那將是整齊的。
這里的問題是您不能部分地專門化函數,而構造函數是一個函數。 您要么完全專門化它們,要么根本不專門。
解決此問題的常見方法是使用標簽分發,但是在您的特定用例中,這要簡單一些...使用static_cast
template < typename TType, int n >
class Field
{
public:
Field( float f )
: _type( static_cast<TType>(f) )
{ }
protected:
TType _type;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.