考虑以下代码:
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/