如果特定的C ++类型具有成员,则排除继承的成员

问题描述 投票:3回答:3

我想检测特定类型是否具有成员:直接和不是继承的结果

目的是确定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; 
}

我想检测特定类型是否具有成员:直接而不是继承的结果。目的是确定特定类型是否“具有特征”,例如序列化的能力。 ...

c++ inheritance c++14 detection typetraits
3个回答
3
投票

有一个巧妙的技巧可以帮助解决这个问题。

&B::member的类型实际上是void (A::*)(),而不是void (B::*)()(如果继承了member


2
投票

这可能对您有用:


1
投票

使用&B::membervoid (A::*)()的事实,您可能会这样做

© www.soinside.com 2019 - 2024. All rights reserved.