如何专门化模板构造函数
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;
};
演示相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 只在模板中专门化构造函数,保持最佳性能和整洁的界面
- 如何专门化模板构造函数模板
- 按参数C++类型专门化重载构造函数
- 如何专门化模板构造函数
- 构造函数模板专门化对析构函数给出了未定义的引用
- 模板类的专门化(数组作为构造函数的输入)