[英]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.