__if_exists 陳述式

__if_exists語句會測試指定的識別碼是否存在。 如果識別項存在,就會執行指定的陳述式區塊。

語法

__if_exists ( identifier ) {
statements
};

參數

identifier
要測試其是否存在的識別項。

語句
如果 識別碼 存在,則執行一或多個語句。

備註

警告

若要達到最可靠的結果,請使用 __if_exists 下列條件約束下的 語句。

  • __if_exists將 語句套用至簡單類型,而非範本。

  • __if_exists 語句套用至類別內部或外部的識別碼。 請勿將 __if_exists 語句套用至區域變數。

  • 只在函 __if_exists 式主體中使用 語句。 在函式主體之外, __if_exists 語句只能測試完整定義的型別。

  • 當您對多載函式進行測試時,無法對特定形式的多載進行測試。

語句的 __if_exists 補充是 __if_not_exists 語句。

範例

請注意,這個範例會使用範本,但不建議這樣做。

// the__if_exists_statement.cpp
// compile with: /EHsc
#include <iostream>

template<typename T>
class X : public T {
public:
   void Dump() {
      std::cout << "In X<T>::Dump()" << std::endl;

      __if_exists(T::Dump) {
         T::Dump();
      }

      __if_not_exists(T::Dump) {
         std::cout << "T::Dump does not exist" << std::endl;
      }
   }
};

class A {
public:
   void Dump() {
      std::cout << "In A::Dump()" << std::endl;
   }
};

class B {};

bool g_bFlag = true;

class C {
public:
   void f(int);
   void f(double);
};

int main() {
   X<A> x1;
   X<B> x2;

   x1.Dump();
   x2.Dump();

   __if_exists(::g_bFlag) {
      std::cout << "g_bFlag = " << g_bFlag << std::endl;
   }

   __if_exists(C::f) {
      std::cout << "C::f exists" << std::endl;
   }

   return 0;
}

輸出

In X<T>::Dump()
In A::Dump()
In X<T>::Dump()
T::Dump does not exist
g_bFlag = 1
C::f exists

另請參閱

選取範圍陳述式
關鍵字
__if_not_exists 陳述式