C++: nested class of a template class

后端 未结 4 2090
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 13:09

Consider the following code:

template < typename T >
struct A
{
    struct B { };
};

template < typename T >
void f( typename A::B ) {          


        
4条回答
  •  醉话见心
    2020-12-10 13:26

    How can I avoid explicitly specifying int while calling f?

    You'll need a little help from struct B.

    template < typename T >
    struct A
    {
        struct B 
        { 
            static T getType(); // no impl required 
        };
    };
    
    #define mytypeof(T) (true?0:T)
    
    template < typename T, typename U >
    void f( T t, U ) { } // U will be T of A::B
    

    Calling it with the following:

    f(x, mytypeof(x.getType()));
    

    Alternatively, you could abstract mytypeof(x.getType()) away by introducing another function which f calls, so you could have your original f(x). e.g.

    template < typename T, typename U >
    void b( T t, U ) { } // U will be T of A::B
    
    template < typename T >
    void f( T t )
    {
        b(t, mytypeof(t));
    }
    

    You could then call f(x).

提交回复
热议问题