Template parameter: class enum, class or enum

Consider the following class:

template <class Endianness>
class bitcode
{};

      

C Endianness

, which may be? default_endianness

, little_endian

Or big_endian

.

The question is this: according to C ++ 14 and the following C ++ 17, what will / will be the best and most common? (by general I mean those used (or will be used) by the standard library or boost

. (+ and why?)

// The enum option
enum enum_endianness {default_endianness, little_endian, big_endian};

// The enum class option
enum class enum_class_endianness {default_endianness, little_endian, big_endian};

// The class option
class class_default_endianness{}; 
class class_little_endian{}; 
class class_big_endian{}; 

      

(Note: of course the declaration bitcode

will depend on the preferred option.)

+3


source to share


3 answers


You need to choose what comes your way:



  • enum

    : This is mainly for backward compatibility.
  • enum class

    : Can only be used when you know all the tags in advance.
  • class

    : Anyone can enter new tags, and you can make tags contain data.
+2


source


The choice is somewhat subject, but if you want to use it as a template parameter (for your class template, for example bitcode

) I would stick with the class / struct tags. This tends to make templating easier to program than mixing things templated by type with templated by specific constant values.



0


source


enum class

is the most appropriate. It is a type-safe, restricted enumeration. You can compare values ​​using an operator ==

, and you can apply specialization and subtraction using template parameters.

enum

is an unlisted enumeration. They are mostly seen as a backward compatibility feature with C ++ 98 and C. Values ​​will be implicitly converted to int

, but those integer values ​​will be meaningless.

class

gives you the submit tags. While this will work, you will have no ==

and operators !=

, which can lead to overuse of templates and overloads.

Another pattern to consider is the type pattern: a class that contains static data members and functions, so you don't need to add additional template parameters.

enum class endianness {little_endian, big_endian};

class little_endian_traits {
    static const enum endianness endianness = endianness::little_endian;
};

class big_endian_traits {
    static const enum endianness endianness = endianness::big_endian;
};

typedef little_endian_traits default_endian_traits; // depending on platform

template< class traits >
class bitcode;

      

0


source







All Articles