How to detect if a method is virtual?

后端 未结 2 1138
情书的邮戳
情书的邮戳 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 <type_traits>
    
    template <class T>
    using void_t = void;
    
    template <class T, T v1, T v2, class = std::integral_constant<bool, true>>
    struct can_be_compaired: std::false_type { };
    
    template <class T, T v1, T v2>
    struct can_be_compaired<T, v1, v2, std::integral_constant<bool, v1 == v2>>: std::true_type { };
    
    template <class T, class = void>
    struct has_virtual_f: std::false_type { };
    
    template <class T>
    struct has_virtual_f<T, void_t<decltype(&T::f)>>{
        constexpr static auto value = !can_be_compaired<decltype(&T::f), &T::f, &T::f>::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<NV>::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

    0 讨论(0)
  • 2020-12-08 01:40

    There is probably no way to determine if a specific method is virtual. I say this because the Boost project researched traits for years and never produced such a traits test.

    However, in C++11, or using the Boost library, you can use the is_polymorphic<> template to test a type to see if the type has virtual functions. See std::is_polymorphic<> or boost::is_polymorphic<> for reference.

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