具有编译时验证的constexpr构造函数 [英] constexpr constructor with compile time validation

查看:85
本文介绍了具有编译时验证的constexpr构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个带有constexpr-ness选项的类。而且,当然,我想利用编译时错误检查。

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.

每个 constexpr 函数,当给定的参数不是常量表达式时,包含的构造函数必须在运行时也能工作。这就是为什么您每次在 constexpr 函数中的 static_assert 函数参数上均无法编译的原因。

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.

但是对于构造函数来说,问题仍然没有解决,因为 constexpr 构造函数似乎必须没有任何主体...所以看来我不能在那使用异常抛出!

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!

任何想法吗?

推荐答案

以下方法可能会有所帮助:

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;
}

这篇关于具有编译时验证的constexpr构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆