本文介紹了如何檢查類中是否存在成員名稱(變量或函數),無論是否指定類型?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
這個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
class
must 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
B
is base ofS
&void B::Bar ()
is present, thenHasMember_Bar<S, void (B::*)()>::value
orHasMember_Bar<S, void (S::*)()>::value
orHasMember_Bar<S>::value
will givefalse
這篇關于如何檢查類中是否存在成員名稱(變量或函數),無論是否指定類型?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!