Wednesday, May 12, 2010

STL/Boost template based meta programming

Here is some experiment of the Arbitrary overload and Concept Check using C++ template.
#include
//is_integral
template struct is_integral{
    enum {value=false};
};

template<> struct is_integral{
    enum {value=true};
};

//Enable if
template struct enable_if { }; //default
template struct enable_if{
    typedef T type;
};

//Arbitary ovlerload: only allow integer Foo : Substitute failure is not an error
template
     typename enable_if::value, T>::type Foo(T x){return x*x;}


//Concept check
template void ignore_unused_variable_warning(const T&) { }

template void require_boolean(const T& t)
{
    bool x=t;
    ignore_unused_variable_warning(x);
}

template struct Comparable{
  void constraints(){
      require_boolean(a==b);
      require_boolean(a!=b);
   }
   T a,b;
};

template void function_requires(Concept t){
   void (Concept::*x)()=&Concept::constraints; //Force compiler to compile the constraints code
}

template void NeedCompare(T t){
      function_requires(Comparable());
};


struct Data{
public:
 Data operator*(const Data& data){return Data();}
private:
 Data& operator=(const Data &);
};

int main()
{
   is_integral a;
   is_integral b;
   Data data;
   std::cout<<"A:"<<<" B:"<<
   int x=Foo(12);
   //Foo(12.3); //Error no matching function for call to Foo(double)
   //NeedCompare(data) ; //no match for ‘operator==’ in
   NeedCompare(12);

}

No comments: