Can one access the template parameter outside of a template without a typedef?

后端 未结 2 1559
日久生厌
日久生厌 2020-12-16 22:27

A simple example:

template // this template parameter should be usable outside!
struct Small {
   typedef _X X; // this is tedious!
   X f         


        
相关标签:
2条回答
  • 2020-12-16 22:36

    Depending on what you're doing, template template parameters might be a better option:

    // "typename X" is a template type parameter. It accepts a type.
    // "template <typename> class SomeSmall" is a template template parameter.
    // It accepts a template that accepts a single type parameter.
    template<typename X, template <typename> class SomeSmall> 
    struct Big {
       SomeSmall<X> bar; // We pass X to the SomeSmall template.
       X toe; // X is available to this template.
    }; 
    
    // Usage example:
    
    template<typename X>
    struct Small { 
       X foo; 
    };
    
    struct MyType {};
    
    // The foo member in Small will be of type MyType.
    Big<MyType, Small> big;
    
    0 讨论(0)
  • 2020-12-16 22:40

    Yes, define a second "getter" template with partial specialization.

    template< typename >
    struct get_Small_X; // base template is incomplete, invalid
    
    template< typename X > // only specializations exist
    struct get_Small_X< Small< X > > {
        typedef X type;
    };
    

    Now instead of Small<X>::X you have typename get_Small_X< Small<X> >::type.

    By the way, _X is a reserved identifier, so you shouldn't use it for anything. X_ is a better choice.


    Advanced topic: template introspection.

    While I'm thinking about it, you don't need to define this separately for every template. A single master template should do it.

    This compiles in Comeau, I know there are rules about matching template template arguments but I think it's OK… template template arguments are forbidden from the master template in partial specialization.

    template< typename >
    struct get_first_type_argument;
    
    template< template< typename > class T, typename X >
    struct get_first_type_argument< T< X > > {
        typedef X type;
    };
    
    template< typename X >
    struct simple;
    
    get_first_type_argument< simple< int > >::type q = 5;
    

    This only works with "unary" templates but could be adapted in C++0x for the general case.

    0 讨论(0)
提交回复
热议问题