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

后端 未结 5 2014
陌清茗
陌清茗 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:11

    Can you try below (it is not partial specialization):

    template
    class X
    {
    };
    
    template<>
    class X<1>
    {
      template
      struct Y{};
    };
    
    template<>
    class X<2>
    {
      template
      struct Y{};
    };
    

    I doubt if the answer is that simple !!

    Edit (Mocking Partial specialization): @Xeo, I was able to compile following code and seems to be fullfilling.

    template
    struct X
    {
      struct Unused {};  // this mocking structure will never be used
    
      template  // if 2 params passed-->ok; else default='Unused'
      struct Y{};
    
      template 
      struct Y{}; // This is specialization of above, define it your way
    };
    
    int main()
    {
      X<1>::Y o1;  // Y called
      X<2>::Y o2; // Y called
    }
    

    Here, however you can use X<1>, X<2> interchangeably. But in the broader example you mentioned, that is irrelevant. Still if you need, you can put checks for I = 1 and I = 2.

提交回复
热议问题