Kulluk007
Kulluk007

Reputation: 972

C++ class specifier alignas option via template

Can C++ template parameters be used to control specifiers on the class itself to minimize some code duplication?

For example: I have a class that I'd like to use both in a concurrent context (and container) with the alignas specifier, and also in a single-threaded context without the alignas specifier. The size of the class is small (20B) -- less than a cache line. I do need to copy between the two classes. Right now I have duplicated code for the two definitions of the two classes which are the same, mostly, other than the said specifier. Can templates or otherwise allow a single definition, one with alignas and one without?

Upvotes: 2

Views: 587

Answers (1)

Brian Bi
Brian Bi

Reputation: 119382

You can do it like this:

template <size_t alignment = 0>
class alignas(alignment) C {
    // ...
};

Now C<> will have the default alignment for its definition (since alignas(0) is ignored) while you could use e.g. C<16> to force an alignment of 16.

Upvotes: 4

Related Questions