等値比較可能かどうか調べるテンプレート in C++0x

アバター
tk-xleader
記事: 158
登録日時: 14年前
連絡を取る:

等値比較可能かどうか調べるテンプレート in C++0x

投稿記事 by tk-xleader » 14年前

要するに、operator==で比較ができるか?というのを調べるテンプレートです。

CODE:

#include
#include
#include

template
class has_equal{
	template
	struct null_value{
		static U& value;
	};

	template
	static std::true_type test(U*,decltype(null_value::value==null_value::value)* = 0); //※ここでSFINAEが行われる。
	static std::false_type test(void*);
	
public:
	typedef decltype(test(static_cast(0))) type;
	static const bool value = type::value;
};

struct sample1{
};

int main(){
	std::cout::value::value::value<<std::endl;
}
実行結果
true
true
false

※のところのdecltypeのなかにテストしたい式(関数呼び出し、演算子の適用などなんでも)を入れれば、Tにそれが適用可能かどうかが検査できます。
検索結果「C++0x SFINAE」 by Google

コメントはまだありません。