How to detect if a method is virtual?

后端 未结 2 1149
情书的邮戳
情书的邮戳 2020-12-08 00:37

I tried to make a traits to find if a method is virtual: (https://ideone.com/9pfaCZ)

// Several structs which should fail depending if T::f is v         


        
2条回答
  •  抹茶落季
    2020-12-08 01:17

    The code isn't perfect but it basically passes the tests (at least in all clangs available on wandbox and gcc since 7.):

    #include 
    
    template 
    using void_t = void;
    
    template >
    struct can_be_compaired: std::false_type { };
    
    template 
    struct can_be_compaired>: std::true_type { };
    
    template 
    struct has_virtual_f: std::false_type { };
    
    template 
    struct has_virtual_f>{
        constexpr static auto value = !can_be_compaired::value;
    };
    
    struct V  { virtual void f() { }      };
    struct NV {         void f() { }      };
    struct E  {                           };
    struct F  { virtual void f() final{ } }; // Bonus (unspecified expected output)
    
    int main() {
       static_assert( has_virtual_f< V>::value, "");
       static_assert(!has_virtual_f::value, "");
       static_assert(!has_virtual_f< E>::value, "");
       static_assert( has_virtual_f< F>::value, "");
    }
    

    [live demo]


    The relevant standard parts that theoretically let the trait fly: [expr.eq]/4.3, [expr.const]/4.23

提交回复
热议问题