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

jwf*_*arn 8 c++ gcc templates

我有使用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

};
Run Code Online (Sandbox Code Playgroud)

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

sth*_*sth 9

我错误地期望从另一个模板类派生的模板类能够直接使用继承的typedef和函数吗?

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

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

void f6() { this->foo(); }
Run Code Online (Sandbox Code Playgroud)