且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法测试 C++ 类是否具有默认构造函数(编译器提供的类型特征除外)?

更新时间:2022-02-10 22:37:18

抱歉回答可能自己的问题.

Sorry for answering may own question.

谷歌搜索我发现我们无法检查类是否具有构造函数或析构函数的实际原因是,用于检测类是否具有成员的已知技术是基于获取成员的地址.但是构造函数和析构函数没有名字,我们不能取它们的地址.

Googling I have found that the actual reason we can not check if a class has constructor or a destructors is that, the known technique used to detect if a class has a member is based on taking the address of the member. But constructors and destructors have no name, we can not take the address of them.

如果我们不能取地址,我看不出有什么方法可以让编译器在不直接实例化的情况下对构造做出反应,但在这种情况下,在编译时没有检测到,而是一个错误.

If we can not take the address, I don't see a way to make the compiler react to a construction without instantiating it directly, but in this case there is no detection at compile time but an error.

所以为了回答我自己的问题,我会说使用当前的技术是不可能检测到它们的,并且需要编译器支持.但是 C++ 已经揭示了很多惊喜,在特定时间不可能实现的事情,可以使用另一种技术来揭示.

So to answer my own question, I would say that with the current techniques it is not possible to detect them and compiler support is needed. But C++ has revealed a lot of surprises, and things that were not possible at a given time, were revealed are possible using another technique.

我希望 C++ 语言专家正在阅读并给出更清晰的解释.

I hope a C++ language expert is reading that and can give a more clear explanation.