C++14 ã® Generic lambdas 㧠SFINAE ãã® 2
昨日書いたコードã¯ãã¾ãæå³ããªãã£ãã®ã§ç°¡åãªã©ããã¼ãæ¸ãã¦ã©ã ãå¼ãå¤éå®ç¾©ã§å¼ã³åºããããã«ãã¦ã¿ã¾ããã
ãããªã SFINAE ã使ãæå³ãåºã¦ããããªã
[ã½ã¼ã¹]
#include <iostream> #include <string> template<typename F1, typename F2> struct overload_impl : F1, F2{ using F1::operator(); using F2::operator(); overload_impl(F1 const& f1, F2 const& f2) : F1(f1), F2(f2){} }; template<typename F1, typename F2> overload_impl< typename std::decay<F1>::type, typename std::decay<F2>::type > overload(F1&& f1, F2&& f2){ return {f1, f2}; } int main(){ auto twice = overload( [](auto x) ->typename std::enable_if< std::is_integral<decltype(x)>{}, decltype(x) >::type{ std::cout << x << " << 1" << std::endl; return x << 1; }, [](auto x) ->typename std::enable_if< !std::is_integral<decltype(x)>{}, decltype(x) >::type{ std::cout << x << " + " << x << std::endl; return x + x; } ); std::cout << twice(10) << std::endl; std::cout << twice('!') << std::endl; std::cout << twice(3.14f) << std::endl; std::cout << twice(std::string("homu")) << std::endl; auto plus = overload( [](auto a, auto b) ->decltype(a + b){ return a + b; }, [](char const* str, auto b) ->decltype(std::string(str) + b){ return std::string(str) + b; } ); std::cout << plus(1, 2) << std::endl; std::cout << plus(2.5, 0.125) << std::endl; std::cout << plus(2.5, 5) << std::endl; std::cout << plus("homu", "mami") << std::endl; std::cout << plus("homu", std::string("mado")) << std::endl; // error // std::cout << plus(3.14f, "homu") << std::endl; return 0; }
[åºå]
10 << 1 20 ! << 1 B 3.14 + 3.14 6.28 homu + homu homuhomu 3 2.625 7.5 homumami homumado
SFINAE ã¯é©å½ã§ãããã¾ããããªæãã§ãã
ã¡ãªã¿ã« overload ã®ã©ããã¼ã¯ C++11 ã§ãæµç¨ãããã¨ã¯å¯è½ã§ãã
ã©ã ãå¼ãé¢æ°ãªãã¸ã§ã¯ãã§ãªããã°ä½¿ç¨ã§ãã¾ãããå°å³ã«ä¾¿å©ã
ãã¨こういう処理ãçµã¿è¾¼ãã§ããã¨æ´ã«ä¾¿å©ãªæ°ãããã
[ã³ã³ãã¤ã©]
- clang++ (LLVM) 3.4 20131004(trunk)