首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++模板法

C++模板法
EN

Stack Overflow用户
提问于 2013-11-19 21:32:41
回答 2查看 128关注 0票数 1

我编写了STL basic_string类的简化版本:

代码语言:javascript
复制
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之间进行转换,我可以简单地这样做:

代码语言:javascript
复制
int main( void )
{
    str as = "foo";
    wstr ws = convert<char, wchar_t>( as );
}

但是,我希望有一个允许这样的转换的模板方法,而不是这种功能的方法。这很可能是错误的,但以下是我想要做的:

代码语言:javascript
复制
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
{
    // ...
}

然后:

代码语言:javascript
复制
int main( void )
{
    str as = "foo";
    wstr ws = as.convert<wchar_t>();
}

可以吗?

谢谢你的帮助!

PS :忘了提到我不想使用C++11特性。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-19 21:41:59

这几乎是可能的-您可以有一个成员函数模板,但它不能是virtual。因此,如果这对您来说没有问题,那么将virtual从声明中删除,您就可以设置了。

要了解为什么成员函数模板不能是virtual,请考虑虚拟成员函数最常见的实现--虚拟函数表。这是一个指向函数的指针表,为每个虚拟函数存储一个指针。一个虚拟成员函数模板需要存储多少个指针?一个convert<char>,一个convert<wchar_t>,一个convert<int>,一个convert<int*>,一个convert<int**>,一个convert<std::vector<int> >,一个.

问题是可以从模板中实例化任意多个函数。没有办法对他们进行动态调度。(注意,在所有其他动态调度实现中也出现了类似的问题--模板只是潜在的无限多个函数)

票数 1
EN

Stack Overflow用户

发布于 2013-11-19 23:00:27

为什么不直接添加一个模板构造函数呢?

代码语言:javascript
复制
template<typename chrT>
class strT
{
public:
    template<typename otherT>
    strT(otherT* o) { ... }
}

要实现转换,可以为chrTotherT的不同可能性专门化构造函数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20082526

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档