1

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_);
4

1 回答 1

0

In C++ you should not define a constant as a macro. 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.

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.

Here is my current <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.

于 2013-12-19T17:50:27.053 回答