c++模板编程之反射相关-判断类型是否有什么

c++模板编程之反射相关-判断类型是否有什么,第1张

c++模板编程之反射相关-判断类型是否有什么

已知 c++是不支持类似 java 的反射的,那么如果我们想知道一个类是否有某些成员,我们该怎么办呢,下面引入 c++模板编程技巧来,提供一个相对可行的办法

#include 
#include 

using namespace std;

template
struct isInvokeAble {
 public:
    template()(declval()...))>
    static true_type test(void *);

    template
    static false_type test(...);

 public:
    constexpr static auto value = decltype(test(nullptr))::value;
};


class funcValidPolicy {
 public:
    template
    static false_type Valid(...);

    template()(declval()...))>
    static true_type Valid(void *);
};

template
struct TypeT {
    using type = T;
};

template
constexpr auto type = TypeT{};

template
T ValueT(TypeT);

auto is_valid = [](auto f) {
    return [](auto ...args) {
        return decltype(funcValidPolicy::template Valid(nullptr)){};
        //return isInvokeAble::value;
    };
};

// 判断类是否有 first()函数
auto has_first_func = is_valid(
        [](auto t) -> decltype(ValueT(t).first()) {}
);

struct First_Func {
    void first() {
        cout << "XX::first" << endl;
    }
};


// 判读类是否有 first变量
auto has_first_member_value = is_valid(
        [](auto t) -> decltype(ValueT(t).first) {}
);

struct First_Mem {
    int first;
};


// 判断类是否可构造
auto isConstructible = is_valid(
        [](auto t)-> decltype(decltype(ValueT(t))()){}
        );

struct CanConstruct {};

struct CanNotConstruct {
 private:
    CanNotConstruct() = default;
};

int main() {
    cout << has_first_func(type) << endl;
    cout << has_first_member_value(type) << endl;

    cout << isConstructible(type) << endl;
    cout << isConstructible(type) << endl;
}

输出

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4993505.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存