conditional (SFINAE) override

后端 未结 1 1707
萌比男神i
萌比男神i 2020-12-19 04:36

I\'m trying to do this:

struct A
{
  virtual int f() const { return 0; }
};

template 
struct B : A
{
  template 

        
1条回答
  •  爱一瞬间的悲伤
    2020-12-19 04:50

    Try this:

    template 
    struct B : A
    {
      ...
    };
    
    temlate 
    struct B::type>:
      A
    {
      virtual int f() const override { return 1; }
    };
    

    where we have two versions of B, one for which the condition is true (the enable_if one), one for which the condition is false (the default one).

    If you wanted to be able to reuse your default B implementation, you could even do this:

    template 
    struct B : A
    {
      ...
    };
    
    template 
    struct B::type>:
      B
    {
      virtual int f() const override { return 1; }
    };
    

    where we inherit from the "false" case in the "true" case. But that is a bit dirty to me -- I'd rather put the common implementation in some third spot (B_impl) rather than that hack. (That also lets you static assert that the second argument is void in the first case of B).

    0 讨论(0)
提交回复
热议问题