首页 > 解决方案 > 使用类检查方法是否存在

问题描述

我正在尝试创建一个类型特征来执行编译时检查是否存在具有类类型的方法。下面是我实现的。我不确定为什么它不起作用。

T = 检查方法的类型。

R = 方法的返回类型。

P = 方法的参数类型。

template<typename T, typename R, typename P>
struct HasBarImpl {
    template<typename> static std::false_type Test(...);

    template<typename U>
    static auto Test(P* p) ->
        std::enable_if_t<std::is_same_v<decltype(declval(U).Bar(p)), R>, std::true_type>;

    static constexpr bool value = std::is_same<decltype(Test<T>(nullptr)), std::true_type>::value;
};

template<typename T, typename R, typename P>
constexpr bool HasBar = HasBarImpl<T, R, P>::value;


struct Foo {
    void Bar(int*) {}
};


TEST_CASE("Check for method's existence") {
    bool r = false;
    if constexpr (HasBar<Foo, void, int>) {
        r = true;
    }

    CHECK(r == true); // Fails
}

标签: c++

解决方案


推荐阅读