简体   繁体   English

模板和嵌套类型查找

[英]Templates and nested type lookup

I have a hierarchy of template classes implementing a CRTP like pattern. 我有一个模板类的层次结构,用于实现类似CRTP的模式。 I don't understand why the name lookup fails in the lines marked with errors, and succeeds in the line marked "no errors here". 我不明白为什么名称查找在标有错误的行中失败,而在标有“此处无错误”的行中成功。

class CPublishedTypes
{
    public:
    typedef int published_t;
};

template<class Derived, class PublishedTypes> class Cbase: public PublishedTypes
{
    public:
        Cbase():ibase_(42){}
    private:
        published_t ibase_; //error: 'published_t' does not name a type       
};

template<class Derived> class Cmiddle : public Cbase<Derived, CPublishedTypes>
{    
    public:
        Cmiddle():imiddle_(42){}
    private:
        published_t imiddle_; //error: 'published_t' does not name a type    
};

class Cderived : public Cmiddle<Cderived>
{
    public:
        Cderived():iderived_(42){}
    private:
        published_t iderived_; // No errors here
};

int main(int argc, char *argv[])
{
    Cderived derived;
    return 0;
}

Using 'typename' doesn't help. 使用'typename'没有帮助。

The C++ FAQ describes a similar but not identical issue here: http://www.parashift.com/c++-faq/nondependent-name-lookup-types.html C ++常见问题解答在此处描述了类似但不相同的问题: http : //www.parashift.com/c++-faq/nondependent-name-lookup-types.html

Cbase inherits publicly from PublishedTypes, which is a template parameter , but it's not a template class . Cbase公开继承自PublishedTypes,后者是模板参数 ,但不是模板 So I don't see why CPublishedTypes::published_t is inaccessible. 所以我看不到为什么CPublishedTypes :: published_t无法访问。

Cderived inherits from Cmiddle which in turn inherits from Cbase. Cderived继承自Cmiddle,后者又继承自Cbase。 So I don't see why I don't need a typename to access CPublishedTypes::published_t here. 所以我不明白为什么我不需要类型名称来访问CPublishedTypes :: published_t。

What am I missing in the name lookup rules? 名称查找规则中我缺少什么?

typename PublishedTypes::published_t

and

typename Cbase<Derived, CPublishedTypes>::published_t
// or simpler
typename Cmiddle::published_t

respectively, will work. 分别将工作。

They're types that are depending on a template parameter (and can't be lookup up until the template gets instantiated) and thus need to be both qualified and prepended by typename . 它们是取决于模板参数的类型(在实例化模板之前无法查找),因此需要同时进行限定和typename前缀。

Types dependent on the template parameter need to be prefixed with typename and, in case of template base classes, the name of the parent class. 依赖于模板参数的类型必须以typename为前缀,如果是模板基类,则必须以父类的名称为前缀。 In the last example, however, the class is not a template and this is thus not necessary as type lookup for Cderived is not delayed until template instantiation, so the regular lookup rules apply. 但是,在最后一个示例中,该类不是模板,因此这不是必需的,因为Cderived类型查找不会延迟到模板实例化之前,因此将应用常规查找规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM