【c++11】static_assert:静的断言type traits:タイプフィーチャー

1330 ワード

static_assertはコンパイル時の断言チェックを提供します
1、static_assertとassertの違い:
assert(式):実行時に断言し、式はfalseであり、実行時に固定されたエラー情報を印刷し、プログラムを終了する.    static_assert(式、「コンパイラに表示させたいエラー情報」):コンパイル時に断言し、式はfalseであり、コンパイル時に所与のエラー情報を表示する.
式はtrueで、どちらも何もしません.
assert(true);
static_assert(true, "will do nothing");
assert(false); // assert : , ( cpp 、 ) 
static_assert(false, "make a error message"); //  , :error C2338: make a error message
色から見分けられます:static_assertはC++キーワードみたい?assertはカスタムタイプ(パラメータ付きマクロ)です
2、type traitsはいくつかのclassで、コンパイル時にタイプに関する情報を提供します.ヘッダファイルでそれらを見つけることができます
//  static_assert type traits 
template 
auto add(T1 t1, T2 t2) -> decltype(t1 + t2)
{
	//  T1、T2 integral, 
	static_assert(std::is_integral::value, "Type T1 must be integral");
	static_assert(std::is_integral::value, "Type T2 must be integral");

	return t1 + t2;
}

void test()
{
	std::cout << add(1, 3.14) << std::endl;  // error C2338: Type T2 must be integral
	std::cout << add("one", 2) << std::endl; // error C2338: Type T1 must be integral

	auto r = add(3L, '2');			 // ok! long、char 
	// typeid , type traits 
	std::cout << typeid(r).name() << std::endl; // long
}