How to check if a member name (variable or function) exists in a class, with or without specifying type?(如何检查类中是否存在成员名称(变量或函数),无论是否指定类型?)
问题描述
这个Q是以下内容的扩展:
模板化检查类成员函数是否存在?
This Q is an extension of:
Templated check for the existence of a class member function?
是否有任何实用程序可以帮助您找到:
Is there any utility which will help to find:
- 成员名是否存在于类中?该成员可以是变量或方法.
- 指定成员的类型应该是可选的
推荐答案
C++03
#define HasMember(NAME)
template<class Class, typename Type = void>
struct HasMember_##NAME
{
typedef char (&yes)[2];
template<unsigned long> struct exists;
template<typename V> static yes Check (exists<sizeof(static_cast<Type>(&V::NAME))>*);
template<typename> static char Check (...);
static const bool value = (sizeof(Check<Class>(0)) == sizeof(yes));
};
template<class Class>
struct HasMember_##NAME<Class, void>
{
typedef char (&yes)[2];
template<unsigned long> struct exists;
template<typename V> static yes Check (exists<sizeof(&V::NAME)>*);
template<typename> static char Check (...);
static const bool value = (sizeof(Check<Class>(0)) == sizeof(yes));
}
用法:只需使用您想要查找的任何成员调用宏:
Usage: Simply invoke the macro with whatever member you want to find:
HasMember(Foo); // Creates a SFINAE `class HasMember_Foo`
HasMember(i); // Creates a SFINAE `class HasMember_i`
现在我们可以使用HasMember_X来检查任何class中的X,如下所示:
Now we can utilize HasMember_X to check X in ANY class as below:
#include<iostream>
struct S
{
void Foo () const {}
// void Foo () {} // If uncommented then type should be mentioned in `HasMember_Foo`
int i;
};
int main ()
{
std::cout << HasMember_Foo<S, void (S::*) () const>::value << "
";
std::cout << HasMember_Foo<S>::value << "
";
std::cout << HasMember_i<S, int (S::*)>::value << "
";
std::cout << HasMember_i<S>::value << "
";
}
捕获:
- 在方法的情况下,如果我们不提及类型,那么
class不得有重载方法.如果有,那么这个技巧就失败了.即,即使命名成员出现不止一次,结果也会是false. - 如果成员是基类的一部分,那么这个技巧就失败了;例如如果
B是S的基础 &void B::Bar()存在,则HasMember_Bar或::valueHasMember_Bar或::valueHasMember_Bar将给出::valuefalse
- In case of methods, if we don't mention the type then the
classmust not have overloaded methods. If it has then this trick fails. i.e. even though the named member is present more than once, the result will befalse. - If the member is part of base class, then this trick fails; e.g. if
Bis base ofS&void B::Bar ()is present, thenHasMember_Bar<S, void (B::*)()>::valueorHasMember_Bar<S, void (S::*)()>::valueorHasMember_Bar<S>::valuewill givefalse
这篇关于如何检查类中是否存在成员名称(变量或函数),无论是否指定类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查类中是否存在成员名称(变量或函数),无
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
