Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 empty flag classes

In some of the unique_lock constructors in C++11 one can pass some classes like a flag, i.e.

auto lock = std::unique_lock<std::mutex> lock(m, std::defer_lock);

where std::defer_lock is defined as

struct defer_lock {}

Why is it done this way, and not with an enum?

I tried to apply this to a small code sample, but I couldn't get it compiling:

class A {};
void foo(A a) {}

int main() {
  foo(A); // error: 'A' does not refer to a value
}

When I put the parentheses like foo(A()); it works, but I don't see the difference to the STL. Why does this behave differently there?

like image 904
lucas clemente Avatar asked Nov 10 '12 23:11

lucas clemente


2 Answers

Using a different type to mark a certain operation rather than an enum makes the choice of code path being taking a compile-time choice rather than a run-time choice. The implementations of the different functions can also be drastically different.

like image 57
Dietmar Kühl Avatar answered Oct 19 '22 17:10

Dietmar Kühl


Actually, std::defer_lock is not defined as you write, but as

constexpr std::defer_lock_t defer_lock = std::defer_lock_t();

That's why your version "mimicking" (badly) the standard library definition doesn't work; change your definition to eg.

struct A {} A;

and it will work. (or, try slightly more appealing struct A_t {} A)

like image 42
jpalecek Avatar answered Oct 19 '22 17:10

jpalecek