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

using namespace std ;

template <typename T>
void show(const T& value)
{
    cout << "*" << value << "*" << endl;
}

template <typename U, typename... T>
void show(const U& head, const T&... tail)
{
    cout << "(" << head << ")"  ;
    show(tail...);
}

template < class T, size_t length >
class String
{
   static_assert(length < 100, "length is too big");
   T str_data[length];
};

template < class T1, class T2 >
auto mul(T1 a, T2 b) -> decltype(a * b)
{
  static_assert(is_integral<T1>::value,"T1, please input integral value");
  static_assert(is_integral<T2>::value,"T2, please input integral value");

   return a * b;
};

int main()
{
    show(" ppp ") ;
    show(100,234.567," hello kitty ",300) ;

   mul(1,5);
   mul(1,5.5);

   String< int, 100 > a1;
   String< int, 90 > a2;
   return 0;
}

 

$ g++ --std=c++0x x.cpp -o x.exe


x.cpp: In instantiation of ?
x.cpp:44:   instantiated from here
x.cpp:23: error: static assertion failed: "length is too big"
x.cpp: In function ?
x.cpp:42:   instantiated from here
x.cpp:31: error: static assertion failed: "T2, please input integral value"

 

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

using namespace std ;

string getname(int x)
{
  switch (x)
  {
    case 0: return "zero";
    case 1: return "one";
    case 2: return "two";
  }
  return "I need to learn to count";
}

int getlength(const string& s)
{
  return s.length();
}

template <typename T, typename F>
auto execute(const T& t, F func) -> decltype(func(t))
{
  return func(t);
}

int main()
{
    cout << execute("hello", getlength) << endl;
    cout << execute(1, getname) << endl;
}

 

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

hedgezzz 發表在 痞客邦 留言(0) 人氣()