Re: Function Overload for tr1::tuple<T>, How To?
Terry G wrote:
I wish I could overload Log, so the tuples of tuples would recursively
work.
I'm so close -- but maybe like Deadhorse Point Utah State Park.
The basic problem is that you can't partially specialize template
functions. The way around that is to make such functions members of
template classes, and partially specialize the template classes. Like this:
#include <tuple>
#include <iostream>
#include <ostream>
using std::tr1::tuple; using std::tr1::get; using std::tr1::make_tuple;
using std::cout;
template <class Ty> struct Logger
{
static void print(const Ty& t)
{
cout << t;
}
};
template <> struct Logger< tuple<> >
{
static void print(const tuple<>&)
{
cout << "()\n";
}
};
template <class A0> struct Logger< tuple<A0> >
{
static void print(const tuple<A0>& t)
{
cout << '(';
Logger<A0>::print(get<0>(t));
cout << ')';
}
};
template <class A0, class A1> struct Logger< tuple<A0, A1> >
{
static void print(const tuple<A0, A1>& t)
{
cout << '(';
Logger<A0>::print(get<0>(t));
cout << ", ";
Logger<A1>::print(get<1>(t));
cout << ')';
}
};
template <class Ty>
void Log(const Ty& t)
{
Logger<Ty>::print(t);
cout << '\n';
}
int main()
{
const char *hello = "hello";
Log(make_tuple(3, hello));
Log(make_tuple(4, make_tuple(4.5, hello)));
return 0;
}
Compiled with gcc 4.0.2 and Dinkumware's TR1, this is what I get:
/home/pete/work$ a.out
(3, hello)
(4, (4.5, hello))
/home/pete/work$
--
-- Pete
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]