,因为模板布尔递延应该评估为假(你的问题) ....
这是因为在struct A
的constexpr
的。
constexpr
符能够在编译时评估bool
值
取出constexpr
而建,你会发现其中的差别。
为什么你static_assert
不工作:
static_assert
期望一个bool_constexpr
。
DEFERRED
只是bool,只有在我们实例化时,模板类体内的值才是已知的。
尝试使用以下代码,我在struct B
的内部添加了另一个bool constexpr
,命名为test
。并将该变量传递给static_assert
。现在您的static_assert
工作。
//g++ 5.4.0
#include <iostream>
struct A { static constexpr bool Value = false; };
template <bool DEFERRED> struct B {
static constexpr bool test = false;
static_assert(test, "Failed");
};
class XYZ {
public:
template <class X = A, class Y = B<X::Value>> int SomeFunction()
{
return 0;
}
};
int main()
{
XYZ xyz;
xyz.SomeFunction();
}
你会发现输出:
source_file.cpp:8:6: error: static assertion failed: Failed
static_assert(test, "Failed");
^
现在struct B
的test
值更改为true
。
它的工作原理,没有错误。
还有另外一种情况,分配给DEFERRED
可变test
如下图所示:
template <bool DEFERRED> struct B {
static constexpr bool test = DEFERRED;
static_assert(test, "Failed");
};
上面说的只是static_assert
的作品,如果你在实例化的main(),像下面。
B<false> b;
“Static_assert”是编译时断言。它有效当你有本地bool_constexpr。下面添加了一些测试代码。 – Naidu