本文介紹了如何檢查類(lèi)中是否存在成員名稱(chēng)(變量或函數(shù)),無(wú)論是否指定類(lèi)型?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
這個(gè)Q是以下內(nèi)容的擴(kuò)展:
模板化檢查類(lèi)成員函數(shù)是否存在?
This Q is an extension of:
Templated check for the existence of a class member function?
是否有任何實(shí)用程序可以幫助您找到:
Is there any utility which will help to find:
- 成員名是否存在于類(lèi)中?該成員可以是變量或方法.
- 指定成員的類(lèi)型應(yīng)該是可選的
推薦答案
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));
}
用法:只需使用您想要查找的任何成員調(diào)用宏:
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`
現(xiàn)在我們可以使用HasMember_X
來(lái)檢查任何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 << "
";
}
捕獲:
- 在方法的情況下,如果我們不提及類(lèi)型,那么
class
不得有重載方法.如果有,那么這個(gè)技巧就失敗了.即,即使命名成員出現(xiàn)不止一次,結(jié)果也會(huì)是false
. - 如果成員是基類(lèi)的一部分,那么這個(gè)技巧就失敗了;例如如果
B
是S
的基礎(chǔ) &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
這篇關(guān)于如何檢查類(lèi)中是否存在成員名稱(chēng)(變量或函數(shù)),無(wú)論是否指定類(lèi)型?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!