Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum vs variable, to store non-type template parameter value. (within Int2Type<int v> template)

Tags:

c++

c++11

Going through Modern C++ Design by Andrei Alexandrescu, I am unable to understand the reason for using unnamed, unscoped enum, to store the non-type parameter. Why not use a variable directly.

Does it have any advantages?

template <int v>
struct Int2Type
{
   enum { value = v }; //why not use int value = v; which compiles fine
};

Extra (if that helps): The template is intended to be used as a "type generator" to select different functions at compile time.

like image 236
User 10482 Avatar asked Jan 22 '26 10:01

User 10482


1 Answers

The main reason to use enum instead of static const int or C++11 static constexpr int is that that enum gives you true prvalue, pretty much like literal int. That becomes important when issues of ODR manifest itself.

For example, following piece of code works fine (complete example):

void foo(const int& x) {
    std::cout << "X: " << x;
}

struct V {
    enum {value = 42; }
};

void bar() {
    foo(V::value);
}

On the other hand, following definition of struct exhibits undefined behavior (ODR violation):

struct V {
    static const int value = 42;
    // same with static constexpr int value = 42;
};

The reason for this is that binding reference to the value (when calling foo) ODR-uses value when it is a const member. All ODR-used variables have to be defined.

However, since references can't bind to enum members (and literals) a temporary is created, to which reference is bound to, so there is nothing to define. This is a very useful feature.

like image 69
SergeyA Avatar answered Jan 24 '26 07:01

SergeyA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!