如何在C ++ 14中检查类是否具有指针 [英] How to check if class has pointers in C++14

查看:85
本文介绍了如何在C ++ 14中检查类是否具有指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上了课:

struct A { // has no pointer members, POD - it's fine
  int a, b;
  char c;
};

struct B { // has no pointer members, but not POD - it's still fine
  int a, b;
  std::string s;
};

struct C { // has pointer members, it's not fine
  int a,b;
  char* cs;
};

我需要在编译时检测是否有任何类具有struct C的属性,即具有指针作为成员.

I need to detect in compile time if any class has the properties of struct C, i.e. has pointers as members.

简短的推理:我需要确保可以通过复制或分配(例如struct A)或通过提供用户定义的serialize()将用户定义的类型安全地序列化并反序列化到某些缓冲区.和deserialize()方法(例如struct Bstruct c).

Short reasoning: I need to assure a user-defined type can be safely serialized and deserialized to some buffer by copying or assignment (e.g. struct A) or by providing user-defined serialize() and deserialize() methods in the class (e.g. struct B and struct c).

如果BC没有实现这些方法,则编译应会失败,但是如果A没有这些方法,则编译应会成功.

If B or C do not have these methods implemented, then compilation should fail, but if A does not have the methods, then the compilation should succeed.

更新:

检查类是否具有指针数据成员的解决方案仅适用于:

struct D {
  int* p; // the pointer must be named 'p'
};

此问题是不同的情况.我们可以重新打开吗?

This issue is a different case. Can we reopen, please?

推荐答案

从C ++ 17开始,这根本不可能.

As of C++17, this is simply not possible.

您可以测试许多特征,但是没有特征可以按照您需要的方式检查数据成员. std::is_pod<>(将在C ++ 20中弃用)是最好的.

You can test for a number of traits, but there is no trait that checks data members the way you need. std::is_pod<> (which will be deprecated in C++20) is the best you can get.

这篇关于如何在C ++ 14中检查类是否具有指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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