在模板中,您会看到 Daniel Frey 的 explained。在模板之外,单独使用 static_assert 是不可能的,但可以在宏和字符串化运算符 # 的帮助下完成:
#define VERIFY_POD(T) \
static_assert(std::is_pod<T>::value, #T " must be a pod-type" );
对于带有 gcc 4.8.1 的 struct non_pod { virtual ~non_pod() {} }; 类型,VERIFY_POD(non_pod) 给出
main.cpp:4:2: error: static assertion failed: non_pod must be a pod-type
static_assert(std::is_pod<T>::value, #T " must be a pod-type" );
^
main.cpp:15:2: note: in expansion of macro 'VERIFY_POD'
VERIFY_POD(non_pod);
如果您和我一样不想在错误消息中看到标记 #T " must be a pod-type",那么您可以在宏定义中添加额外的一行:
#define VERIFY_POD(T) \
static_assert(std::is_pod<T>::value, \
#T "must be a pod-type" );
有了这个,前面的例子产生:
main.cpp: In function 'int main()':
main.cpp:4:2: error: static assertion failed: non_pod must be a pod-type
static_assert(std::is_pod<T>::value, \
^
main.cpp:14:2: note: in expansion of macro 'VERIFY_POD'
VERIFY_POD(non_pod);
^
当然,错误消息的确切外观取决于编译器。使用 clang 3.4 我们得到
main.cpp:14:5: error: static_assert failed "non_pod must be a pod-type"
VERIFY_POD(non_pod);
^~~~~~~~~~~~~~~~~~~
main.cpp:3:23: note: expanded from macro 'VERIFY_POD'
#define VERIFY_POD(T) \
^
1 error generated.