[英]For identical static_assert messages, should I rely on MACROS?
static_assert has the following syntax, which states that a string literal is required. static_assert具有以下语法,该语法指出需要字符串文字。
static_assert ( bool_constexpr , string literal );
static_assert(bool_constexpr, 字符串文字 );
Since an instance of a string CAN'T be observed at compile time, the following code is invalid: 由于在编译时无法观察到字符串的实例 ,因此以下代码无效:
const std::string ERROR_MESSAGE{"I assert that you CAN NOT do this."};
static_assert(/* boolean expression */ ,ERROR_MESSAGE);
I have static asserts all over my code, which say the same error message. 我在我的代码中都声明了静态断言,它们都说相同的错误消息。 Since a string literal is required, would it be best to replace all the repetitive string literals with a MACRO, or is there a better way?
由于需要字符串文字,因此最好将所有重复的字符串文字替换为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_);
In C++ you should not define a constant as a macro. 在C ++中,你不应该定义一个常量宏。 Define it as a constant.
将其定义为常量。 That's what constants are for.
这就是常量的用途。
Also, names beginning with underscore followed by uppercase letter, such as your _ERROR_MESSAGE_
, are reserved to the implementation. 另外,以下划线开头的大写字母的名称(例如
_ERROR_MESSAGE_
)保留给实现。
That said, yes , it's good idea to use a macro for static asserts, both to ensure a correct string argument and to support compilers that possibly don't have static_assert
, but this macro is not C style constant: it takes the expression as argument, and provides that expression as the string message. 就是说, 是的 ,最好使用宏进行静态断言,以确保正确的字符串参数并支持可能没有
static_assert
编译器,但是此宏不是C样式常量:它将表达式作为参数,并提供该表达式作为字符串消息。
Here is my current <static_assert.h>
: 这是我当前的
<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 )
As you can see there are some subtleties involved even when the compiler does have static_assert
. 如您所见,即使编译器确实具有
static_assert
也涉及一些细微问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.