问题描述
可以定义 Traits 类来检查 C++ 类是否具有成员变量、函数或类型(参见 此处).
Traits classes can be defined to check if a C++ class has a member variable, function or a type (see here).
奇怪的是,ConceptTraits 不包括特征检查 C++ 类是否定义了默认构造函数或给定构造函数?
Curiously, the ConceptTraits do not include traits to check if a C++ class defines a default constructor or given constructor?
可以用traits来检查构造函数的存在吗?如果是,如何?如果没有,为什么不可能?
Can traits be used to check the constructor presence? If yes, how? If not, why it is not possible?
推荐答案
抱歉回答可能自己的问题.
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.
这篇关于有没有办法测试 C++ 类是否具有默认构造函数(编译器提供的类型特征除外)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!