c++ - static_assert 依赖于类模板

标签 c++ class c++11 compile-time static-assert

考虑以下代码:

template <unsigned int N>
struct myclass
{
    unsigned int f() {return N;}
    unsigned int g() {static_assert(N > 0, ""); return N-1;}
};

问题: 我是否保证以下代码可以编译:

myclass<0> c;
c.f();

但以下不会:

myclass<0> c;
c.f();
c.g();

最佳答案

是的,你有这个保证。来自 [temp.inst]/11,强调我的:

An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, or a static data member of a class template that does not require instantiation.

如果您不调用 g() ,它不需要实例化,所以调用 myclass<0>{}.f() 应该没有问题.

这与允许您使用 std::vector 的保证相同。和 std::map只要您不执行诸如调用 resize() 之类的操作,类型就不是默认可构造的和 operator[] , 分别。

作为 Jarod42 points out 的后续行动, 是显式实例化 myclass<0>将产生断言,因为从 [temp.explicit]/8:

An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its members (not including members inherited from base classes and members that are templates) that has not been previously explicitly specialized in the translation unit containing the explicit instantiation, except as described below.

异常(exception)情况不适用于此处。

关于c++ - static_assert 依赖于类模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30788104/

相关文章:

android - 通过在 qt 中从 C++ JNI 发送字符串在 Android 中显示 Toast

java - 泛型类型出现问题 - Java

c++ - 将 unique_ptrs 从一个 vector move 到另一个 vector

具有明确舍入策略的整数除法 C++ 函数

c++ - 针对 libstdc++ 和 libc++ 链接 iOS 应用程序

c++ - 使用 boost 和 python 绑定(bind)在 osx 上构建 32 位版本的 libtorrent

c++ - 如何为 random_shuffle 编写 range-v3 Action ?

.net - 使用 Windows Crypto API 的 Windows 2000 和 Windows 2003 RC2 加密/解密?

php - 哪种初始化 php 属性的方法更好?

html - 如何在显示 : none? 后使用类来显示特定元素