このコードは、テンプレートを使用したコンパイル時のアサートのデモです。次のコマンドラインを使用して g++ (4.4.7) でのみコンパイルできることがわかりました。
$ g++ -std=c++98 a.cpp -o a
icc (13.0.1) も Visual C++ (80x86 用の 14.00.50727.762) でもコンパイルできません。icc の場合、次のようなエラー メッセージが生成されます。
$ icpc a.cpp -o a
a.cpp(13): error: non-integral operation not allowed in nontype template argument
COMPILE_TIME_ASSERT(true && "err msg");
^
a.cpp(13): error: class "CompileTimeAssert<<error-constant>>" has no member "Check"
COMPILE_TIME_ASSERT(true && "err msg");
^
compilation aborted for a.cpp (code 2)
ただし、次のようなアサーションtrue && "err msg"
がランタイム assert で広く使用されていることがわかりました。 assertにカスタム メッセージを追加しますか?
質問は
- これは、適切なコンパイル オプションを使用するだけで、コードを変更せずに解決できますか?
- できない場合、カスタム メッセージを使用してコンパイル時にアサートする代替方法はありますか?
デモコードは次のように表示されます。
#include <iostream>
template<bool B> class CompileTimeAssert { };
template<> class CompileTimeAssert<true> {
public:
static inline void Check() { }
};
#define COMPILE_TIME_ASSERT(b) CompileTimeAssert<(b)>::Check()
int main()
{
COMPILE_TIME_ASSERT(true && "err msg");
std::cout<<(true && "err msg")<<std::endl;
return 0;
}