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

后端 未结 5 2024
陌清茗
陌清茗 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条回答
  •  旧时难觅i
    2020-12-08 08:08

    Here you go:

    http://ideone.com/AdEfl

    And the code:

    #include 
    
    template 
    struct Traits
    {
      struct inner{};
    };
    
    template <>
    struct Traits<1>
    {
      struct inner{
        template
        struct impl{
          impl() { std::cout << "impl" << std::endl; }
        };
      };
    };
    
    template <>
    struct Traits<2>
    {
      struct inner{
        template
        struct impl{
          impl() { std::cout << "impl" << std::endl; }
        };
      };
    };
    
    template
    struct Test{};
    
    template
    struct Foo{};
    
    template
    struct arg{};
    
    template<
      template class T,
      class P1, int I
    >
    struct Test< T > >{
      typedef typename Traits::inner inner;      
    };
    
    template<
      template class T,
      class P2, int I
    >
    struct Test< T, P2 > >{
      typedef typename Traits::inner inner;      
    };
    
    // and a bunch of other partial specializations
    
    int main(){
    
      typename Test > >::inner::impl b;
      typename Test > >::inner::impl c;
    }
    

    Explanation: Basically it's an extension of the idea of partial specialization, however the difference is that rather than specializing within Test, delegate to a specific class that can be specialized on I alone. That way you only need to define versions of inner for each I once. Then multiple specializations of Test can re-use. The inner holder is used to make the typedef in the Test class easier to handle.

    EDIT: here is a test case that shows what happens if you pass in the wrong number of template arguments: http://ideone.com/QzgNP

提交回复
热议问题