Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

c++ - constexpr constructor with compile time validation

I'd like to build up a class with the option of constexpr-ness. And, of course, I'd like to take advantage of compile time error check.

Every constexpr function, constructor included, must work also at runtime, when the given parameters are not constant expression. That's should be the reason why every time you use static_assert in a constexpr function upon a function parameter it fails to compile.

Said so, I've read that one can use the exception throwing mechnanism, since when the function is called upon a constant expression, those exceptions can be evaluated at compile time. If that works, for functions the problem is solved.

But the problem is still not solved for constructors, since constexpr constructors seem to must have no body... so it looks like I can't use exception throwing from there!

Any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Following may help:

class A
{
public:
    constexpr A(int i) : i(i != 42 ? throw 42 : i) {}
private:
    int i;
};

int main(int argc, char *argv[])
{
    constexpr A a1(42);
    //constexpr A a2(41); // Compile error as expected.
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...