Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should literal classes be used in C++?

Can someone tell me when are literal classes needed in C++?
I am getting a little confused from constexpr constructors, constexpr members, and I can't see what the point is. I'd like to see some practical use of it.

Also I'd want to know if a set member function needs to be constexpr, i.e.:

constexpr void set_num(int a) { num = a; }
like image 670
TGO Avatar asked Jan 13 '13 20:01

TGO


People also ask

What is literal class?

A literal class type is a class type that has a trivial destructor, is either an aggregate type or has at least one non-move, non-copy constexpr constructor, and all of its base classes and non-static data members are non-volatile literal types.

What is a literal type CPP?

Literal types are the types of constexpr variables and they can be constructed, manipulated, and returned from constexpr functions. Note: the standard doesn't define a named requirement with this name. This is a type category defined by the core language. It is included here as a named requirement only for consistency.


1 Answers

constexpr fixes a problem in C++98 when using numeric limits. Before C++11 an expression such as

std::numeric_limits<short>::max()

can not be used as integral constant, although it is almost equal to macro INT_MAX. with C++11, such an expression is declared as constexpr so that, for example, you can use it to declare arrays or in compile-time computations (metaprogramming):

std::array<float,std::numeric_limits<short>::max()> a;
like image 159
billz Avatar answered Oct 21 '22 15:10

billz