加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

模板基类typedef和函数的更好的C语法?

发布时间:2020-12-16 04:55:25 所属栏目:百科 来源:网络整理
导读:我有使用VC9(Microsoft Visual C 2008 SP1)编译的代码,但没有使用GCC 4.2(在Mac上,如果这很重要).如果我填写足够的限定符和关键字,我可以强制它在GCC中工作,但这似乎不对. 这是一个展示我的问题的最小代码示例: template typename N struct B { typedef N n
我有使用VC9(Microsoft Visual C 2008 SP1)编译的代码,但没有使用GCC 4.2(在Mac上,如果这很重要).如果我填写足够的限定符和关键字,我可以强制它在GCC中工作,但这似乎不对.

这是一个展示我的问题的最小代码示例:

template< typename N >
struct B {
    typedef N n_type;                     // can derived class access typedef?
    void foo() {}                         // can derived class access function?
};

template< typename N >
struct D : public B<N> {

    typedef B<N> b_type;
    typedef typename b_type::n_type bn_type;

    void f1( n_type ) {}                  // ERROR: 'n_type' has not been
                                          // declared

    void f2( typename B<N>::n_type ) {}   // OK,verbose

    void f3( b_type::n_type ) {}          // ERROR: 'struct B<N>::n_type' is 
                                          // not a type

    void f4( typename b_type::n_type ) {} // OK,verbose

    void f5( bn_type ) {}                 // OK,verbose typedefs

    void f6() { foo(); }                  // ERROR: there are no arguments to
                                          // 'foo' that depend on a template
                                          // parameter,so a declaration of
                                          // 'foo' must be available

    void f7() { b_type::foo(); }          // OK,verbose

};

我错误地期望从另一个模板类派生的模板类能够直接使用继承的typedef和函数吗?有没有比我迄今为止提出的更好的方法呢?

解决方法

Am I wrong to expect a template class derived from another template class to be able to use inherited typedefs and functions directly?

是的,这通常不会像你期望的那样工作. C名称查找规则指定仅在模板化基类中搜索名称(如果它取决于模板参数(如果它是“依赖名称”)).如果名称不依赖于模板参数,则不会在那里搜索. (另见this C++ FAQ Lite entry)

要从依赖基类调用函数,最简单的方法是使用this-&gt ;,因为这总是隐式的依赖名称:

void f6() { this->foo(); }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读