我编写了STL basic_string类的简化版本:
template<typename chrT>
class strT
{
protected:
chrT * m_pcBuf;
size_t m_nLen;
public:
strT( void );
strT( const chrT * pcStr );
strT( const strT<chrT> & rsStr );
virtual ~strT( void );
virtual inline size_t len( void ) const;
virtual int cmp( const strT<chrT> & rsStr ) const;
virtual inline const chrT & operator [] ( size_t nPos ) const;
virtual inline chrT & operator [] ( size_t nPos );
virtual bool & operator == ( const strT<chrT> & rsStr ) const;
virtual bool & operator != ( const strT<chrT> & rsStr ) const;
virtual bool & operator < ( const strT<chrT> & rsStr ) const;
virtual bool & operator > ( const strT<chrT> & rsStr ) const;
virtual bool & operator <= ( const strT<chrT> & rsStr ) const;
virtual bool & operator >= ( const strT<chrT> & rsStr ) const;
virtual inline strT<chrT> & operator = ( const strT<chrT> & rsStr );
virtual inline operator chrT * ( void );
protected:
void _alloc( size_t nLen );
void _realloc( size_t nLen );
public:
static const size_t none;
};
template<typename inchr, typename outchr>
strT<outchr> convert( const strT<inchr> & rsIn );
typedef strT<char> str;
typedef strT<wchar_t> wstr;目前,如果我想在char和wchar_t之间进行转换,我可以简单地这样做:
int main( void )
{
str as = "foo";
wstr ws = convert<char, wchar_t>( as );
}但是,我希望有一个允许这样的转换的模板方法,而不是这种功能的方法。这很可能是错误的,但以下是我想要做的:
template<typename chrT>
class strT
{
// ...
public:
template<typename outchr>
virtual strT<outchr> convert( void ) const;
// ...
}
template<typename chrT, typename outchr>
strT<outchr> strT<chrT>::convert<outchr>( void ) const
{
// ...
}然后:
int main( void )
{
str as = "foo";
wstr ws = as.convert<wchar_t>();
}可以吗?
谢谢你的帮助!
PS :忘了提到我不想使用C++11特性。
发布于 2013-11-19 21:41:59
这几乎是可能的-您可以有一个成员函数模板,但它不能是virtual。因此,如果这对您来说没有问题,那么将virtual从声明中删除,您就可以设置了。
要了解为什么成员函数模板不能是virtual,请考虑虚拟成员函数最常见的实现--虚拟函数表。这是一个指向函数的指针表,为每个虚拟函数存储一个指针。一个虚拟成员函数模板需要存储多少个指针?一个convert<char>,一个convert<wchar_t>,一个convert<int>,一个convert<int*>,一个convert<int**>,一个convert<std::vector<int> >,一个.
问题是可以从模板中实例化任意多个函数。没有办法对他们进行动态调度。(注意,在所有其他动态调度实现中也出现了类似的问题--模板只是潜在的无限多个函数)
发布于 2013-11-19 23:00:27
为什么不直接添加一个模板构造函数呢?
template<typename chrT>
class strT
{
public:
template<typename otherT>
strT(otherT* o) { ... }
}要实现转换,可以为chrT和otherT的不同可能性专门化构造函数。
https://stackoverflow.com/questions/20082526
复制相似问题