The __if_exists Statement
__if_exists allows you to conditionally include code depending on whether the specified symbol exists.
__if_exists ( variable ) {
statements
}
where:
- variable
The symbol whose existence you want to test for.
- statements
One or more statements to execute if variable exists.
Remarks
__if_exists can be used to test for the existence of both members and non-members identifiers and can be used to test for the existence of an overloaded function but not for a specific form of the overload.
__if_exists should only be used within the body of a function. Outside of the body of a function __if_exists can only refer to fully defined types. The Visual C++ compiler must know what members a class template has before any instantiations.
__if_not_exists allows you to conditionally include code depending on whether the specified symbol does not exist.
Example
// 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;
}
Output
In X<T>::Dump() In A::Dump() In X<T>::Dump() T::Dump does not exist g_bFlag = 1 C::f exists