Boost logo

Boost :

Subject: [boost] [C++0x] Emulation of scoped enums
From: Beman Dawes (bdawes_at_[hidden])
Date: 2009-03-05 10:37:12


The improved type safety of the C++0x scoped enum feature is attractive,
so I'd like to start using it as it becomes available in compilers.

See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf
for a description. Note that the committee changed the name from
strongly typed enums to scoped enums.

See the attached for a boost/detail header that provides macro wrappers
that use scoped enums if available, otherwise fall back on C++03
namespaces and unscoped enums. It lets a library write:

   BOOST_SCOPED_ENUM_START(algae) { green, red, cyan };
     BOOST_SCOPED_ENUM_END
   ...
   BOOST_SCOPED_ENUM(algae) sample( algae::red );
   void func(BOOST_SCOPED_ENUM(algae));

and then a user can write:

   sample = algae::green;
   func( algae::cyan );

Comments or suggestions appreciated,

--Beman


// scoped_enum_emulation.hpp ---------------------------------------------------------//

// Copyright Beman Dawes, 2009

// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt

// Generates C++0x scoped enums if the feature is present, otherwise emulates C++0x
// scoped enums with C++03 namespaces and enums. The Boost.Config BOOST_NO_SCOPED_ENUMS
// macro is used to detect feature support.
//
// Caution: only the syntax is emulated; the semantics are not emulated and
// the syntax emulation doesn't include being able to specify the underlying type.
//
// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf for a
// description of the feature. Note that the committee changed the name from
// strongly typed enums to scoped enums.
//
// Sample usage:
//
// BOOST_SCOPED_ENUM_START(algae) { green, red, cyan }; BOOST_SCOPED_ENUM_END
// ...
// BOOST_SCOPED_ENUM(algae) sample( algae::red );
// void foo( BOOST_SCOPED_ENUM(algae) color );
// ...
// sample = algae::green;
// foo( algae::cyan );

#ifndef BOOST_SCOPED_ENUM_EMULATION_HPP
#define BOOST_SCOPED_ENUM_EMULATION_HPP

#include <boost/config.hpp>

#ifndef BOOST_NO_SCOPED_ENUMS

# define BOOST_SCOPED_ENUM_START(name) enum class name
# define BOOST_SCOPED_ENUM_END
# define BOOST_SCOPED_ENUM(name) name

#else

# define BOOST_SCOPED_ENUM_START(name) namespace name { enum enum_t
# define BOOST_SCOPED_ENUM_END }
# define BOOST_SCOPED_ENUM(name) name::enum_t

#endif

#endif // BOOST_SCOPED_ENUM_EMULATION_HPP


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