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

前端 未结 3 1192
一整个雨季
一整个雨季 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:19

    Yes, it is possible. I have implemented such behavior in the past by using some metaprogramming tricks. The basic build blocks are:

    BOOST_MPL_HAS_XXX_TRAIT_DEF, to define a metafunction predicate that will evaluate to a true type if the argument is of class type and has a nested type with a given name (context_type in your case).

    http://www.boost.org/doc/libs/1_47_0/libs/mpl/doc/refmanual/has-xxx-trait-def.html

    Boost.EnableIf, to define the specializations based on the previously defined trait.

    http://www.boost.org/libs/utility/enable_if.html # See 3.1 Enabling template class specializations


    Note that you may be able to get that behavior working directly with SFINAE, something like this may work:

    template< typename T, typename Context = void >
    class wrapper { ... }; // Base definition
    
    template< typename T >
    class wrapper< T, typename voif_mfn< typename T::context_type >::type > { ... }; // Specialization
    

    However, I like the expressiveness of the solution based on traits and enable if.

提交回复
热议问题