gpt4 book ai didi

c++ - 如何检测一个方法是否是虚拟的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:53:26 26 4
gpt4 key购买 nike

我试图创建一个特征来查找方法是否为 virtual : ( https://ideone.com/9pfaCZ )

// Several 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, "");

但是我得到了error: 'void Dvf<T>::f() [with T = NV]' marked final, but is not virtual .
如果我不使用 sizeof直接Dvf<T>*check , 我没有编译错误,但是 check不会因为 SFINAE 中的“坏”类型而被丢弃 :( .

检测方法是否为 virtual 的正确方法是什么? ?

最佳答案

代码并不完美,但它基本上通过了测试(至少在 wandbox 和 gcc 7 之后可用的所有 clangs 中):

#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]


理论上让特性飞起来的相关标准件:[expr.eq]/4.3 , [expr.const]/4.23

关于c++ - 如何检测一个方法是否是虚拟的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24197369/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com