Can we have an anonymous struct as template argument?

前端 未结 2 1247
遇见更好的自我
遇见更好的自我 2021-01-11 10:54

The title is pretty self-explanatory, but here\'s a simplified example:

#include 

template 
struct MyTemplate {

    T membe         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 11:24

    Your problem isn't that the struct is unnamed, it's that the struct is declared locally. Using local types as template arguments is not permitted in C++03. It will be in C++0x though, so you might try upgrading your compiler.

    EDIT: Actually, your problem is that inside a template argument list isn't a legal place to put a class definition, with or without a name, according to the C++ standard.

    litb points out that although it fits into the C++0x grammar, defining a type here is forbidden by [dcl.type]:

    A type-specifier-seq shall not define a class or enumeration unless it appears in the type-id of an alias-declaration (7.1.3) that is not the declaration of a template-declaration.

    simple-template-id:
        template-name < template-argument-list_opt >
    
    template-argument-list:
        template-argument ..._opt
        template-argument-list , template-argument ..._opt
    
    template-argument:
        constant-expression
        type-id
        id-expression
    
    type-id:
        type-specifier-seq abstract-declarator_opt
    
    type-specifier-seq:
        type-specifier attribute-specifier-seq_opt
        type-specifier type-specifier-seq
    
    type-specifier:
        trailing-type-specifier
        class-specifier
        enum-specifier
    
    class-specifier:
        class-head { member-specification_opt }
    

    For a while I had a question about typedef names, but litb cleared that up. They are allowed as template arguments via:

    trailing-type-specifier:
        simple-type-specifier
        elaborated-type-specifier
        typename-specifier
        cv-qualifier
    
    simple-type-specifier:
        :: opt nested-name-specifier_opt type-name
        :: opt nested-name-specifier template simple-template-id
        char
        char16_t
        char32_t
        wchar_t
        bool
        short
        int
        long
        signed
        unsigned
        float
        double
        void
        auto
        decltype-specifier
    
    type-name:
        class-name
        enum-name
        typedef-name
        simple-template-id
    

提交回复
热议问题