Boost logo

Boost Users :

From: Eric Niebler (eric_at_[hidden])
Date: 2005-05-11 12:36:30


Sliwa, Przemyslaw (London) wrote:
>
> I would like to write a template which depending on the argument type
> does different things.
>
> For example the pseudo code:
>
> template <class T, class C>
> foo(T& nT, C& nC)
> {
> // common code;
> if(T==C)
> // specific code;
> .....
>
> // again common code;
> }
>
> Can the template meta programming help me in this case?

It may. It depends on whether "specific code" compiles when T!=C. If it
does, you could do this:

template <class T, class C>
void foo(T& nT, C& nC)
{
     // common code
     if(boost::is_same<T,C>::value)
       { /* specific code */ }
     // again common code
}

where is is_same<> is defined in boost/type_traits/is_same.hpp. If
"specific code" doesn't compile when T!=C, you need to get fancier. An
overloaded helper function is the way to go:

template<class T, class C>
void specific_code(T&, C&) {}

template<class T>
void specific_code(T&, T&)
{
   // specific code here
}

template <class T, class C>
void foo(T& nT, C& nC)
{
     // common code
     specific_code(nT, nC);
     // again common code
}

HTH,

-- 
Eric Niebler
Boost Consulting
www.boost-consulting.com

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net