[英]For identical static_assert messages, should I rely on MACROS?
static_assert具有以下语法,该语法指出需要字符串文字。
static_assert(bool_constexpr, 字符串文字 );
由于在编译时无法观察到字符串的实例 ,因此以下代码无效:
const std::string ERROR_MESSAGE{"I assert that you CAN NOT do this."};
static_assert(/* boolean expression */ ,ERROR_MESSAGE);
我在我的代码中都声明了静态断言,它们都说相同的错误消息。 由于需要字符串文字,因此最好将所有重复的字符串文字替换为MACRO,还是有更好的方法?
// Is this method ok?
// Should I hand type them all instead?
// Is there a better way?
#define _ERROR_MESSAGE_ "danger"
static_assert(/* boolean expression 1*/ ,_ERROR_MESSAGE_);
//... code ...
static_assert(/* boolean expression 2*/ ,_ERROR_MESSAGE_);
//... code ...
static_assert(/* boolean expression 3*/ ,_ERROR_MESSAGE_);
在C ++中,你不应该定义一个常量宏。 将其定义为常量。 这就是常量的用途。
另外,以下划线开头的大写字母的名称(例如_ERROR_MESSAGE_
)保留给实现。
就是说, 是的 ,最好使用宏进行静态断言,以确保正确的字符串参数并支持可能没有static_assert
编译器,但是此宏不是C样式常量:它将表达式作为参数,并提供该表达式作为字符串消息。
这是我当前的<static_assert.h>
:
#pragma once
// Copyright (c) 2013 Alf P. Steinbach
// The "..." arguments permit template instantiations with "<" and ">".
#define CPPX_STATIC_ASSERT__IMPL( message_literal, ... ) \
static_assert( __VA_ARGS__, "CPPX_STATIC_ASSERT: " message_literal )
#define CPPX_STATIC_ASSERT( ... ) \
CPPX_STATIC_ASSERT__IMPL( #__VA_ARGS__, __VA_ARGS__ )
// For arguments like std::integral_constant
#define CPPX_STATIC_ASSERT_YES( ... ) \
CPPX_STATIC_ASSERT__IMPL( #__VA_ARGS__, __VA_ARGS__::value )
如您所见,即使编译器确实具有static_assert
也涉及一些细微问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.