Boost logo

Boost :

From: Paul Mensonides (pmenso57_at_[hidden])
Date: 2002-04-24 13:55:58


> Is there a way to detect if TYPE::something exists and is an enumerated
> value, where TYPE is a template parameter? I thought of it for a while but I
> can't see a way to do it.
>
> Giovanni Bajo

BTW, he wants to detect if a given name is an enumerator 'value' not an
enumeration type. For instance,

struct X {
    enum type { value };
};

He wants to detect 'value' not type. I'm wasn't sure if he justed wanted to
detect if a available constant value of a certain name was present or a direct
enumerator only. So, while I don't really see the utility of the entire thing,
this *will* detect if a type has a nested enumerator 'NAME':
---------------------------------------------
typedef char small_t;
typedef char (& large_t)[256]

template<class T> class has_enumerator_NAME {
  private:
    template<class U> class has_NAME {
      private:
        template<int> struct helper;
        template<class V> static small_t check(helper<V::NAME>*);
        template<class V> static large_t check(...);
      public:
        enum { value = sizeof(check<U>(0)) == sizeof(small_t) };
    };
    template<class U> class has_static_const_NAME {
      private:
        #define GEN(name, type) \
          template<const type*> struct name; \
          template<class V> static small_t check(name<&V::NAME>*);
        GEN(a, char)
        GEN(b, signed char)
        GEN(c, unsigned char)
        GEN(d, bool)
        GEN(e, wchar_t)
        GEN(f, short)
        GEN(g, unsigned short)
        GEN(h, int)
        GEN(i, unsigned)
        GEN(j, long)
        GEN(k, unsigned long)
        #undef GEN
        template<class V> static large_t check(...);
      public:
        enum { value = sizeof(check<U>(0)) == sizeof(small_t) };
    };
  public:
    static const bool value =
      has_value<T>::value
      && !has_static_const_value<T>::value;
};

template<class T> const bool has_enumerator_NAME<T>::value;
---------------------------------------------

This eliminates everything but enumerator values.

struct X {
    enum { TYPE = 0 };
};

struct Y {
    static const int TYPE = 0;
};

const int Y::TYPE;

int main() {
    std::cout
        << has_enumerator_NAME<X>::value << '\n' // outputs true
        << has_enumerator_NAME<Y>::value << &std::endl; // outputs false
    return 0;
}

Paul Mensonides


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk