簡體   English   中英

對於相同的static_assert消息,我應該依靠MACROS嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM