Topic: unknown number of parameteres for templates and generic


Author: Greg Herlihy <greghe@pacbell.net>
Date: Mon, 29 Jan 2007 12:18:55 CST
Raw View
On 1/28/07 9:29 AM, in article
1169989226.999027.182150@m58g2000cwm.googlegroups.com, "jam"
<farid.mehrabi@gmail.com> wrote:

> I was reading the documentation for STL`s <functional> today.Having
> C#`s delegates in mind ,a long time has passed since I have reached to
> the disapointing conclusion that in existing versions of C++ compilers
> and standards there is no proper way to define a generic type safe
> template for function objects;We are always bound to know the exact
> number of arguments for templates because no syntax exists for greedy
> templates(ie templates with unspecified number of type arguments).I
> can suggest different syntaxes for such purpose but ellipsis is the
> simplest:

It is possible to declare a C++ function template that will accept a
variable number of arguments. Just place the arguments into a
std::tr1::tuple. The template then uses tuple_size to count the number of
arguments and tuple_element to access each one.

> //syntax:
> template <typename t1,typename t2 ,... typelist>
> //end syntax
> struct funxn{//a generic function object type
> t1 operator(register t2 ob,typelist ob_list){
> //do someting
> .........
> go(ob_list);
> .........
> return  ret;//return a t1
> };
> };

    #include <tr1/tuple> // or <boost/tuple>

    using std::tr1::tuple;
    using std::tr1::tuple_size;
    using std::tr1::tuple_element;

    template <class T, int N = tuple_size<T>::value>
    struct funxn
    {
    };

Now decompose the tuple type into individual parameters via partial
specialization:

    template< class T >
    struct funxn< T, 0 >
    {
       typedef void R;

       void operator ()( )
       {
           // ...
       }
    };

    template< class T >
    struct funxn< T, 1 >
    {
       typedef typename tuple_element<0, T>::type R;

       R operator ()( )
       {
           // ...
       }
    };

    template< class T >
    struct funxn< T, 2>
    {
       typedef typename tuple_element<0, T>::type R;
       typedef typename tuple_element<0, T>::type P1;

       R operator ()( const P1& p1 )
       {
          // ...
       }
    };

> void go(int,double);
>
> static funxn<char,char,int,double> f_ccid;//instantiate the template
>
> void mycode(void){
> char ch=f_ccid('a' ,1 , 1.5);//call the function object
> };

     static funxn< tuple< char, char, int, double> f_ccid;

     int main()
     {

       char ch = _ccid('a', 1, 1.5);

     }

Greg

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]