Quick Q: What is constexpr useful for? -- StackOverflow

Quick A: When you need the constant to be available at compile time.

Today on SO:

What are 'constexpr' useful for?

I really can't find any use of it. My first idea was that I could use it to implement 'Design by Contract' without using macros like this:

struct S
{  
    S(constexpr int i) : S(i) { static_assert( i < 9, "i must be < 9" ); }

    S(int i); //external defintion

    char *pSomeMemory;
};

But this wouldn't compile. I thought we could also use it to reference same-variable without the need of additional memory to be created when we want to avoid the get/setters in order to make instances to one member from users to be read-only:

class S
{ 
private:
    int _i;

public:
    const int & constexpr i = _i;
};

But none of the above actually compiled. Can someone give me some insight why this keyword was being introduced?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.