Template specialization to use default type if class member typedef does not exist

后端 未结 3 1214
误落风尘
误落风尘 2020-12-14 03:44

I\'m trying to write code that uses a member typedef of a template argument, but want to supply a default type if the template argument does not have that typedef. A simpli

3条回答
  •  忘掉有多难
    2020-12-14 04:02

    To answer your addition - your specialization argument passes the member typedef and expects it to yield void as type. There is nothing magic about this - it just uses a default argument. Let's see how it works. If you say Get_Type::type, the compiler uses the default argument of Enable, which is void, and the type name becomes Get_Type::type. Now, the compiler checks whether any partial specialization matches.

    Your partial specialization's argument list is deduced from the original argument list . This will deduce T to Foo and afterwards substitutes that Foo into the second argument of the specialization, yielding a final result of for your partial specialization. That doesn't, however, match the original argument list at all!

    You need a way to yield the void type, as in the following:

    template
    struct tovoid { typedef void type; };
    
    template struct Get_Type { 
        typedef DefaultType Type; 
    };
    template 
    struct Get_Type< T, typename tovoid::type > {
        typedef typename T::Type  Type; 
    };
    

    Now this will work like you expect. Using MPL, you can use always instead of tovoid

    typename apply< always, typename T::type >::type
    

提交回复
热议问题