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

后端 未结 3 1215
误落风尘
误落风尘 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:16

    You can do that by utilizing SFINAE:

    template struct has_type {
        template static char (&test(typename U::Type const*))[1];
        template static char (&test(...))[2];
        static const bool value = (sizeof(test(0)) == 1);
    };
    
    template::value> struct Get_Type {
        typedef DefaultType Type;
    };
    
    template struct Get_Type { 
        typedef typename T::Type Type;
    };
    

提交回复
热议问题