C++14 の Generic lambdas で SFINAE

まぁ Generic lambdas だと多重定義できないのでほとんど意味は無いのですが。

[ソース]

#include <iostream>
#include <type_traits>
#include <string>

int
main(){
    auto plus = [](auto a, auto b)
        ->decltype(a + b){
        return a + b;
    };
    std::cout << plus(1, 2) << std::endl;
    std::cout << plus(std::string("homu"), "mami") << std::endl;
    // error
//  std::cout << plus("homu", "mami") << std::endl;

    auto bit_shift_4 = [](auto x)
        ->typename std::enable_if<
            std::is_arithmetic<decltype(x)>{}, decltype(x)
        >::type{
        return x << 5;
    };
    std::cout << bit_shift_4(4) << std::endl;
    // error
//  std::cout << bit_shift_4(3.14f) << std::endl;

    return 0;
}

[出力]

3
homumami
128


とりあえずやってみたかっただけ。

[コンパイラ]

  • clang++ (LLVM) 3.4 20131004(trunk)