views:

113

answers:

1

__if_exists is a microsoft specific keyword for testing existence of identifiers at compile time:

msdn:__if_exists

It can come in very handy at "faked" template specialization as in some cases it provides a really much more simple, readable and better performing way than other methods like "real" specialization or overloading or whatever.

But now I have to port a big project to gnu c++ and I think I would start a little bit of crying if I would have to find other ways for the (admittedly few) occasions I used it

+1  A: 

That's a crappy keyword in my opinion...

Unfortunately, it doesn't exist in gcc as far as I know, but then I may simply not know about it.

The proper C++ way to handle this is through the use of Concepts, ie adapt the operations carried on the type depending on some requirements.

Usually, it's carried out with traits rather than real concepts, because it's easier to put in place:

template <typename T>
struct has_dump: boost::mpl::false_ {};

And then you dump-enable your types by specializing the has_dump structure.

The simplest is to define 3 methods, one to route, the two others to execute the different branches:

template <typename T>
void dump(T& t, boost::mpl::true_ const& dummy)
{
  t.Dump();
}

template <typename T>
void dump(T& t, boost::mpl::false_ const& dummy)
{
  std::cout << typeid(T).name() << " does not have Dump\n";
}

template <typename T>
void dump(T& t) { dump(t, has_dump<T>()); }

Another use of the type traits would be in conjunction with the enable_if facilities:

template <typename T>
typename boost::enable_if< has_dump<T> >::type dump(T& t)
{
  t.Dump();
}

// disable_if exists too...

Here, instead of a runtime error message, you can get a compile-time error if the type does not have has_dump enabled, not sure if that's you want.

However both those methods are quite cumbersome, since the detection isn't automated. That is why there is the Boost.Concept library.

The idea is that the check will be performed by a Concept object, created to test the requirements, and thus you don't have to specialize traits any longer, which make easier on the development. However I have always found the documentation of Boost.Concept to be somewhat lacking.

Matthieu M.
Well your alternative is also way too complicated for my purpose but I will accept your answer as a "no" if nobody comes up with a real simple "yes" in a few days.
kaptnole
@kaptnole: I agree it's verbose, the whole of concepts was to simply this... let's hope they'll make it in C++1x
Matthieu M.