在 C++11 中,模板中 static_assert 的操作是否应该取决于该模板是否已被实例化?例如,使用以下代码
template <int I>
void sa() { static_assert(0,"Hello."); }
int main(int argc, char *argv[]) { return 0; }
GCC 4.5.0 将使断言失败,并生成“Hello”。信息。 另一方面,Digital Mars Compiler 8.42n 版没有给出任何消息。
最佳答案
GCC 是正确的,其他编译器也是正确的。引用规范中的 14.6p8
If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required.
因此,编译器可以自由拒绝以下内容
template<typename T>
void f() {
static_assert(0, "may trigger immediately!");
static_assert(sizeof(T) == 0, "may trigger immediately!");
}
如果您想安全起见,您必须对其进行安排,以便编译器在实例化之前无法知道 bool 表达式是真还是假。例如通过getvalue<T>::value
获取值, 与 getvalue
作为一个类模板(可以专门化它,所以编译器不可能已经知道 bool 值)。
关于C++11 static_assert 和模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14252840/