更好的C ++语法模板基类typedefs和函数? [英] Better C++ syntax for template base class typedefs and functions?

查看:213
本文介绍了更好的C ++语法模板基类typedefs和函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用VC9(Microsoft Visual C ++ 2008 SP1)编译的代码,但不能用GCC 4.2编译(在Mac上,如果有的话)。如果我在足够的限定词和关键字上堆积,我可以强制它在GCC中工作,但这看起来不正确。

I have code that compiles fine with VC9 (Microsoft Visual C++ 2008 SP1) but not with GCC 4.2 (on Mac, if that matters). If I pile on enough qualifiers and keywords I can force it to work in GCC but this doesn't seem right.

下面是一个展示我的问题的最小代码示例: p>

Here's a minimal code sample exhibiting my problems:

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

};

我期望从另一个模板类派生的模板类能够使用继承的typedefs和直接起作用?

Am I wrong to expect a template class derived from another template class to be able to use inherited typedefs and functions directly? Is there a better way to do this than what I've come up with so far?

推荐答案


有没有更好的方法可以做到这一点? >我期望从另一个模板类派生的模板类能够直接使用继承的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 ++名称查找规则指定仅在模板化基类中搜索名称(如果它依赖于模板参数)(如果它是依赖名称)。如果名称不依赖于模板参数,则不在该处搜索。 (另请参见此C ++ FAQ Lite条目

Yes, this will not generally work as you expect it. The C++ name lookup rules specify that a name is only searched in a templated base classes if it depends on a template parameter (if it is a "dependent name"). If a name does not depend on a template parameter it isn't searched there. (Also see this C++ FAQ Lite entry)

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

To call functions from a dependent base class the most easy way is to use this->, since this is always implicitly a dependent name:

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

这篇关于更好的C ++语法模板基类typedefs和函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆