static_assert の文字列を動的にカスタマイズして表示する方法はありますか?
つまり、次のようなものです。
//pseudo code
static_assert(Check_Range<T>::value, "Value of " + typeof(T) + " type is not so good ;)");
static_assert の文字列を動的にカスタマイズして表示する方法はありますか?
つまり、次のようなものです。
//pseudo code
static_assert(Check_Range<T>::value, "Value of " + typeof(T) + " type is not so good ;)");
いいえ、ありません。
static_assert
ただし、コンパイル時に評価され、エラーの場合、コンパイラはメッセージ自体を出力するだけでなく、インスタンス化スタック (テンプレートの場合) も出力するため、これはそれほど重要ではありません。
この合成例を ideoneで見てみましょう:
#include <iostream>
template <typename T>
struct IsInteger { static bool const value = false; };
template <>
struct IsInteger<int> { static bool const value = true; };
template <typename T>
void DoSomething(T t) {
static_assert(IsInteger<T>::value, // 11
"not an integer");
std::cout << t;
}
int main() {
DoSomething("Hello, World!"); // 18
}
コンパイラは診断を発行するだけでなく、完全なスタックも発行します。
prog.cpp: In function 'void DoSomething(T) [with T = const char*]':
prog.cpp:18:30: instantiated from here
prog.cpp:11:3: error: static assertion failed: "not an integer"
Python または Java と、例外が発生した場合にスタックを出力する方法を知っている場合は、よく知っているはずです。実際には、コール スタックを取得するだけでなく、引数の値 (ここでは型) も取得できるため、さらに優れています。
したがって、動的メッセージは必要ありません:)
標準では、 の 2 番目の引数がstatic_assert
文字列リテラルになるように指定されているため、私が見る限り、そこで計算する機会はありません (プリプロセッサ マクロを除く)。
コンパイラは標準を拡張し、この位置で適切な型の const 式を許可することができますが、コンパイラがそうするかどうかはわかりません。