是否可以检查是否为类定义了成员函数,即使该成员是从未知基类继承的 [英] Is it possible to check if a member function is defined for a class even if the member is inherited from an unknown base class
问题描述
我发现了类似的问题和解答,例如这一个。然而,正如我试验,这个SFINAE测试只成功,如果被测试的成员直接在被测试类中定义。例如下面的类 B
, D1
print HAS
而另外两个打印 NOT HAS
。是否有一种方法来确定一个类是否有一个成员,无论它是由自身定义还是一个基类,并且基类的名称在这种情况下是未知的。动机是,我想写一个通用函数,如果它存在(从基础或非,参数的类型是通用的,沿着其可能的基础的类型),将调用某个方法。
I found similar questions and answers like this one. However, as I tried out, this SFINAE tests only succeeded if the tested member is directly defined in the class being tested. For example the following, class B
, D1
print HAS
while the other two print NOT HAS
. Is there a way to determine that if a class has a member, whether it is defined by itself, or a base class, and the name of the base class is not known in this case. The motivation is that I want to write a generic function that will call a certain method if it exists (from base or not, the type of the parameter is generic, leave along the type of its possible base).
#include <iostream>
class HasFoo
{
public :
typedef char Small;
typedef struct {char; char;} Large;
template <typename C, void (C::*) ()> class SFINAE {};
template <typename C> static Small test (SFINAE<C, &C::foo> *)
{
std::cout << "HAS" << std::endl;
}
template <typename C> static Large test (...)
{
std::cout << "NOT HAS" << std::endl;
}
};
class B
{
public :
void foo () {}
};
class D1 : public B
{
public :
void foo () {} // overide
};
class D2 : public B
{
public :
using B::foo;
};
class D3 : public B {};
int main ()
{
HasFoo::test<B>(0);
HasFoo::test<D1>(0);
HasFoo::test<D2>(0);
HasFoo::test<D3>(0);
}
推荐答案
可能至少在C ++ 03中,我也怀疑在C ++ 11中。
Unfortunately it wouldn't be possible at least in C++03 and I doubt in C++11 also.
几个重要的点:
- 建议的SFINAE只有在方法
public
- 才有效。即使SFINAE可以工作对于基本方法,点(1)
适用;因为private
和protected
继承SFINAE
可能最终无用 - 假设您只想处理
public
方法/继承,
代码HasFoo :: test<> code>可以增强多个
参数,其中基类也可以传递;
std :: is_base_of<>
可用于进一步验证
基本/派生关系;然后对基类
和
- The proposed SFINAE works only if the method is
public
- Even if the SFINAE would have worked for base methods, the point (1)
applies; because for
private
andprotected
inheritance the SFINAE may end up useless - Assuming you may want to deal only with
public
method/inheritance, the codeHasFoo::test<>
can be enhanced for taking multiple parameters where a base class also can be passed;std::is_base_of<>
can be used for further validation of the base/derived relationship; then apply the same logic for base class also
这篇关于是否可以检查是否为类定义了成员函数,即使该成员是从未知基类继承的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!