あちこちに記事が書かれてたりしますが、あえて自分も書いてみます。
SFINAE とは Substitution Failure Is Not An Error の略で、
「テンプレートの置き換えに失敗してもエラーにならない」という、C++ の仕組みのことです。
どういうこっちゃ?って話ですが、
実際にコードと実行結果を見てもらったほうが早いでしょう。
test.cpp
# include <iostream>
struct Custom
{
struct Element {
int value;
};
};
template <typename T>
void Func(typename T::Element* = 0)
{
using namespace std;
cout << "custom" << endl;
}
template <typename>
void Func(...)
{
using namespace std;
cout << "default" << endl;
}
int main()
{
Func<Custom>();
Func<int>();
return 0;
}
output
custom
default
Element を持つ Custom クラスをテンプレート引数にすると上の Func で、
Element を持たない int をテンプレート引数に指定すると下の Func で置き換えられます。
このように、型の特性などで処理を分けたい場合に使えます。
と言っても、現在「これだ!」と思いつくものはありませんが……。
(巷でよく聞く enable_if も有効活用できる気がしないです……。)
ちなみに、今回のサンプルプログラムは以下のサイトを参考にさせていただきました。
SFINAE(substitution failure is not an error) - Faith and Brave - C++で遊ぼう
http://faithandbrave.hateblo.jp/entry/20071108/1194519897