(1) 为什么会提出static_assert?
有人希望使用断言来限制模板的实例化。在static_assert
之前,可用的断言工具有两个:
assert
-
#error
但是assert
是在运行期使用的,#error
是在translation期间使用的,而实例化是在编译器进行的,所以,现有的这两个断言工具都无法满足要求。
(2)如何使用?
语法:
static_assert ( constant-expression , string-literal ) ; //C++11
static_assert ( constant-expression );//C++17
(3)代码示例
- namespace scope
// At namespace scope, the static_assertion declaration
// may be used as an alternative to the #error preprocessor
// directive.
//
static_assert(sizeof(long) >= 8, "64-bit code generation not enabled/supported.");
- class scope
template <class CharT, class Traits = std::char_traits<CharT> >
class basic_string
{
static_assert(tr1::is_pod<CharT>::value, "Template argument CharT must be a POD type in class template basic_string");
// ...
};
block scope
#include <sys/param.h> // for PAGESIZE
class VMMClient
{
public:
int do_something()
{
struct VMPage
{
// ...
};
static_assert(sizeof(VMPage) == PAGESIZE, "Struct VMPage must be the same size as a system virtual memory page.");
// ...
}
// ...
};
double-checking complicated compile-time computation results
template <class T>
class A
{
private:
struct impl_1 {...};
struct impl_2 {...};
static const unsigned sz1 = sizeof(impl_1) < sizeof(impl_2) ? sizeof(impl_2) : sizeof(impl_1);
static const unsigned sz2 = sizeof(T);
static const unsigned sz3 = sz1 + (sz2-1) & ~(sz2-1);
struct impl
{
union
{
impl_1 a;
impl_2 b;
};
T data_[sz3];
static_assert(sizeof(data_) >= sizeof(impl_1), "Design error: Assumption compromised");
static_assert(sizeof(data_) >= sizeof(impl_2), "Design error: Assumption compromised");
};
};
double-checking design assumptions
template <class T, bool>
class container_impl
{
static_assert(!std::tr1::is_scalar<T>::value, "Implementation error: this specialization intended for non-scalars only");
// ...
};
template <class T>
class container_impl<T, true>
{
static_assert(std::tr1::is_scalar<T>::value, "Implementation error: this specialization intended for scalars only");
// ...
};
template <class T>
class container : private container_impl<T, std::tr1::is_scalar<T>::value>
{
// ...
};
网友评论