我想检测特定类型是否具有成员:直接和不是继承的结果。
目的是确定specific类型是否具有“特征”,例如序列化的能力。自然地,并且为了扩展示例,即使父类型具有子类型,子类型也可能无法序列化。]
[使用is_member_function_pointer
或其他检测机制时,继承正在起作用。请注意,即使B没有定义成员,输出仍为“ 1”。
#include <type_traits> #include <iostream> struct A { void member() { } }; struct B : A { }; int main() { std::cout << "B has member? " << std::is_member_function_pointer<decltype(&B::member)>::value << std::endl; }
我能够实现的最接近的结果是使用不可转换的指针(
B**
没有隐式转换为A**
的指针),尽管使用起来有点尴尬。它还强加了与该类型匹配的附加参数,并防止了任何直接继承。#include <type_traits> #include <iostream> struct A { // would match std::declval<B*> as B* -> A*, // hence forcing failure through B** -> A**. // void member(A*) { } void member(A**) { } }; struct B : A { // succeeds compilation aka "found" if not commented // void member(B**) { } }; int main() { // This actually fails to compile, which is OKAY because it // WORKS when used with SFINAE during the actual detection. // This is just a simple example to run. // error: invalid conversion from 'B**' to 'A**' std::cout << "B has member? " << std::is_member_function_pointer< decltype(std::declval<B>().member(std::declval<B**>())) >::value << std::endl; }
我想检测特定类型是否具有成员:直接而不是继承的结果。目的是确定特定类型是否“具有特征”,例如序列化的能力。 ...
有一个巧妙的技巧可以帮助解决这个问题。
&B::member
的类型实际上是void (A::*)()
,而不是void (B::*)()
(如果继承了member
。
这可能对您有用:
使用&B::member
为void (A::*)()
的事实,您可能会这样做