栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;
}

输出

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/395870.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号