C++11 static_assert 和模板实例化

标签 c++ c++11

在 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/

相关文章:

c++ - 无法理解 C++ 中的可变参数模板

c++ - 将模板成员函数传递给模板

c++ - 使用递归的 BST 中序遍历

c++ - gtk_window_set_icon_from_file() 无法正常工作

c++ - 在不设置环境变量的情况下在 Windows 7 中运行 MinGW gcc 编译器

C++ - 使用initializer_list作为参数的模板函数

c++ - 是否有用于多线程内存分配器的验证套件?

c++11 - 使用 std::make_shared 分配 std::weak_ptr

c++ - 以下程序背后的逻辑是什么?

c++ - 为什么 const 左值引用可以引用可变右值引用?