mpl勉強モード
enable_ifを使ってテンプレートメンバー関数を特殊化してみた?
#include <iostream> #include <string> #include <typeinfo> #if defined(__GNUC__) #include <type_traits> #include <cxxabi.h> #endif #if !defined(__GNUC__) template <bool b, class T> struct enable_if; template <class T> struct enable_if<true, T> { typedef T type; }; #else using std::enable_if; #endif #define DECRER_IS_TYPE(name, index) \ template <size_t N>\ struct name\ {\ static const bool value = false;\ };\ \ template <>\ struct name<index>\ {\ static const bool value = true;\ }; DECRER_IS_TYPE(is_hoge_x, 0) DECRER_IS_TYPE(is_hoge_y, 1) DECRER_IS_TYPE(is_hoge_s, 2) #undef DECRER_IS_TYPE struct hoge { int x_; double y_; std::string s_; hoge() : x_(0), y_(1.0), s_("xyuyux") {} template <size_t N> typename enable_if<is_hoge_x<N>::value, int>::type get() const { return x_; } template <size_t N> typename enable_if<is_hoge_y<N>::value, double>::type get() const { return y_; } template <size_t N> typename enable_if<is_hoge_s<N>::value, std::string>::type get() const { return s_; } }; int main(int argc, char** argv) { hoge h; std::cout << std::showpoint; std::cout << h.get<1>() << std::endl; std::cout << h.get<0>() << std::endl; std::cout << h.get<2>() << std::endl; return 0; }
実行結果
1.00000
0
xyuyux