如何检测方法是否是虚拟的? [英] How to detect if a method is virtual?

查看:447
本文介绍了如何检测方法是否是虚拟的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出某个方法是否 virtual :( https:/ /ideone.com/9pfaCZ

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

// Seveval structs which should fail depending if T::f is virtual or not.
template <typename T> struct Dvf : T { void f() final; };
template <typename T> struct Dvo : T { void f() override; };
template <typename T> struct Dnv : T { void f() = delete; };

template <typename U>
class has_virtual_f
{
private:
    template <std::size_t N> struct helper {};
    template <typename T>
    static std::uint8_t check(helper<sizeof(Dvf<T>)>*);
    template<typename T> static std::uint16_t check(...);
public:
    static
    constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t);
};

测试用例:

struct V  { virtual void f(); };
struct NV {         void f(); };
struct E  {                   };
struct F  { virtual void f() final; }; // Bonus (unspecified expected output)

static_assert( has_virtual_f< V>::value, "");
static_assert(!has_virtual_f<NV>::value, "");
static_assert(!has_virtual_f< E>::value, "");

但是我得到了错误:'void Dvf< T& )[with T = NV]'标记为final,但不是虚拟

如果我不使用 sizeof 并直接在 Dvf< T> * 检查,我没有编译错误,但

But I got error: 'void Dvf<T>::f() [with T = NV]' marked final, but is not virtual.
If I don't use sizeof and directly Dvf<T>* in check, I don't have compilation error, but check is not discarded for "bad" type in SFINAE :( .

检查是否正确的方法是检测方法是否 virtual

推荐答案

可能无法确定某个特定方法 virtual 。我这样说是因为 Boost项目研究了

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.

但是,在C ++ 11中,或者使用 Boost库,你可以使用 is_polymorphic<> 模板测试一个类型,看看类型是否有虚函数。 a href =http://en.cppreference.com/w/cpp/types/is_polymorphic =nofollow> std :: is_polymorphic<> 或 boost :: is_polymorphic<> 以供参考。

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.

这篇关于如何检测方法是否是虚拟的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆