Conditional compile-time inclusion/exclusion of code based on template argument(s)?

后端 未结 5 2025
陌清茗
陌清茗 2020-12-08 07:39

Consider the following class, with the inner struct Y being used as a type, eg. in templates, later on:

template
class X{
  templat         


        
5条回答
  •  一个人的身影
    2020-12-08 08:20

    There are two problems here:

    1. enable_if works with partial specialization, not primary templates.
    2. The number of externally-visible arguments is determined by the primary template, of which there may be only one.

    Answer 1.

    As you suggested in chat, a linked list of templates can emulate the variadic parameter pack.

    template
    class X{
      template
      struct Y;
    
      template
      struct Y< list, typename std::enable_if::type > {
          typedef typename list::type t1;
      };
    
      template
      struct Y< list, typename std::enable_if::type > {
          typedef typename list::type t1;
          typedef typename list::next::type t2;
      };
    };
    

    If you end up with next::next::next garbage, it's easy to write a metafunction, or use Boost MPL.


    Answer 2.

    The different-arity templates can be named similarly but still stay distinct if they are nested inside the SFINAE-controlled type.

    template
    class X{
      template
      struct Z;
    
      template
      struct Z< v, typename std::enable_if::type > {
          template
          struct Y{};
      };
    
      template
      struct Z< v, typename std::enable_if::type > {
          template
          struct Y{};
      };
    };
    
    X<1>::Z<>::Y< int > a;
    X<2>::Z<>::Y< char, double > b;
    

提交回复
热议问题