Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are good cases for using __if_exists?

Tags:

c++

visual-c++

When do I use __if_exists without writing tons of crappy code?

Looks like this keyword is like C preprocessor directive, but is processed after preprocessor. And IntelliSense doesn't parse it and highlight code as dead or alive. These together make analysis of code written with __if_exists really non-trivial.

So far I found only one relatively safe case. We have a container class that takes an address of stored object. When a class stored has an overloaded operator& that overloaded operator is called and this causes problems.

So I added the following check:

__if_exists( T::operator& ) {
   static_assert( false );
}

and now the code at least won't compile if there's an operator& member function is the type stored.

IMO this use case is quite clear and easy to read.

What other cases are there of using __if_exists without getting tons of unreadable code?

like image 572
sharptooth Avatar asked Feb 21 '11 14:02

sharptooth


2 Answers

Though I'm not sure this is always possible or useful, __if_exists can be used as static if in D language in a sense.
For example, the following code prints b.

template< bool > struct static_if_t;
template<> struct static_if_t< true > {};
#define STATIC_IF( c )     __if_exists    ( static_if_t< (c) > )
#define STATIC_UNLESS( c ) __if_not_exists( static_if_t< (c) > )

struct X {
  static bool const v = false;
};

STATIC_IF( X::v ) {
  void f() { puts("a"); }
}
STATIC_UNLESS( X::v ) {
  void f() { puts("b"); }
}

int main() {
  f(); // prints "b"
}
like image 92
Ise Wisteria Avatar answered Oct 10 '22 10:10

Ise Wisteria


I think you can use it to distinguish unions and classes, since classes do have constructors and unions don't.

You'd want this in e.g. boost::type_traits::is_class<T> and boost::type_traits::is_union<T>

like image 27
MSalters Avatar answered Oct 10 '22 10:10

MSalters