如何专门化模板构造函数

how to specialize a template constructor

本文关键字:构造函数 专门化      更新时间:2023-10-16

我可以很好地专门化构造函数:

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;
};
演示