Is it possible to specialize a template definition based on the existence of a nested typedef of a template type parameter?

前端 未结 3 1202
一整个雨季
一整个雨季 2021-02-10 02:57

I have a template, template class wrapper, that I would like to specialize based on the existence of typename T::context_type. If

3条回答
  •  無奈伤痛
    2021-02-10 03:13

    That's possible, and there are many ways to implement this. All of them should go back on some trait class has_type so that has_type::value is true if the member typedef exists, and false otherwise. Let's assume we have this trait class already. Then here's one solution, using C++11 template aliases:

    template  class FooImpl
    {
      // implement general case
    };
    
    template  class FooImpl
    {
      // implement specific case
    };
    
    template  using Foo = FooImpl::value>;  // C++11 only
    

    Now to make the typetrait:

    template
    struct has_type
    {
    private:
        typedef char                      yes;
        typedef struct { char array[2]; } no;
    
        template static yes test(typename C::context_type*);
        template static no  test(...);
    public:
        static const bool value = sizeof(test(0)) == sizeof(yes);
    };
    

    If you don't have C++11, or if you don't want to rewrite the entire class, you can make the distinction more fine-grained, e.g. by using std::enable_if, std::conditional, etc. Post a comment if you want some specific examples.

提交回复
热议问题