LoginSignup
6
5

More than 5 years have passed since last update.

シンプルな SFINAE

Last updated at Posted at 2014-05-14

あちこちに記事が書かれてたりしますが、あえて自分も書いてみます。

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

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5