Boost logo

Boost Users :

Subject: Re: [Boost-users] [TypeTraits] Is it possible to detect that type is not exist and use default type?
From: Roman Perepelitsa (roman.perepelitsa_at_[hidden])
Date: 2009-06-30 15:32:14


2009/6/30 Sakharuk, Vlad (GMI Development) <Vlad_Sakharuk_at_[hidden]>

> Here is example:
> class one {
> public:
> typedef someclass internal;
> };
>
> class two {
> // No internal class
> };
>
> class default_internal{
> };
>
> I would like to be able to write something if it possible:
>
> template<class T, class B = if_exist(T::internal) T::internal
> else default_internal > class proc {
> };
>
> So I can use proc with both
>
> proc<one> One;
> proc<two> Two;
>
> without specifying derived type?
>
>

#include <iostream>
#include <boost/mpl/has_xxx.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>

struct someclass {
  static void hello() {
    std::cout << "someclass" << std::endl;
  }
};

struct one {
 public:
  typedef someclass internal;
};

struct two {};

struct default_internal {
  static void hello() {
    std::cout << "default_internal" << std::endl;
  }
};

BOOST_MPL_HAS_XXX_TRAIT_DEF(internal)

// Here Internal is either T::internal
// if it exists or default_internal.
template <class T, class Internal>
struct proc_impl {
  static void hi() {
    Internal::hello();
  }
};

template <class T>
struct get_internal {
  typedef typename T::internal type;
};

template <class T>
struct proc :
  proc_impl<
    T,
    typename boost::mpl::eval_if<
      has_internal<T>,
      get_internal<T>,
      boost::mpl::identity<default_internal>
>::type
> {
};

int main() {
  proc<one>::hi();
  proc<two>::hi();
}

Roman Perepelitsa.



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net