tags:

views:

473

answers:

2

I've created a small utility function for string conversion so that I don't have to go around creating ostringstream objects all over the place

template<typename T>
inline string ToString(const T& x)
{
    std::ostringstream o;
    if (!(o << x))
        throw BadConversion(string("ToString(") + typeid(x).name() + ")");
    return o.str();
}

I want to provide some specialisations of this method for instances where there is no default overloaded << operator for stringstream (i.e. std::pair, std::set, my own classes) and I've run into difficulties with the templating. I will illustrate with the std::pair example, if I want to be able to

string str = ToString(make_pair(3, 4));

the only way I can think of to do it is to define the explicit specialisation for int

template<>
inline string ToString(const pair<int,int>& x)
{
    std::ostringstream o;
    if (!(o << "[" << x.first << "," << x.second << "]"))
        throw BadConversion(string("ToString(pair<int,int>)"));
    return o.str();
}

is there a way I can define this for the generic case?

template<>
inline string ToString(const pair<T1,T2>& x)
{
    std::ostringstream o;
    if (!(o << "[" << x.first << "," << x.second << "]"))
        throw BadConversion(string("ToString(pair<T1,T2>)"));
    return o.str();
}
+13  A: 

Don't specialize the template, but overload it. The compiler will figure out what function template to take by ordering them according to their specialization of their function parameter types (this is called partial ordering).

template<typename T1, typename T2>
inline string ToString(const std::pair<T1, T2>& x) {
    std::ostringstream o;
    if (!(o << "[" << x.first << "," << x.second << "]"))
        throw BadConversion(string("ToString(pair<T1,T2>)"));
    return o.str();
}

In general, partial ordering will result in exactly what you expect. In more detail, consider having these two functions

template<typename T> void f(T);
template<typename T, typename U> void f(pair<T, U>);

Now, to see whether one is at least as specialized as the other one, we test the following for both function templates:

  1. chose some unique type for each template parameter, substitute that into the function parameter list.
  2. With that parameter list as argument, make argument deduction on the other template (make a virtual call with those arguments to that other template). If the deduction succeeds and there is no conversion required (adding const is such one).

Example for the above:

  1. substituting some type X1 into T gives us some type, call it X1. argument deduction of X1 against pair<T, U> won't work. So the first is not at least as specialized as the second template.
  2. substituting types Y1 and Y2 into pair<T, U> yields pair<Y1, Y2>. Doing argument deduction against T of the first template works: T will be deduced as pair<Y1, Y2>. So the second is at least as specialized as the first.

The rule is, a function template A is more specialized than the other B, if A is at least as specialized as B, but B is not at least as specialized as A. So, the second wins in our example: It's more specialized, and it will be chosen if we could in principle call both template functions.

I'm afraid, that overview was in a hurry, i only did it for type parameters and skipped some details. Look into 14.5.5.2 in the C++ Standard Spec to see the gory details. g

Johannes Schaub - litb
Thanks for the great explanation
Jamie Cook
You are welcome :)
Johannes Schaub - litb
Do you really require the checking and throwing exception? I guess compiler will give error when invalid types are passed. Correct?
Appu
hmmm... good point. I don't think I really do. I'll admit that I copied that original block from the internet somewhere and added the specialisations for pair/vector etc. Is there any case where !(o << x) would evaluate to true? I can't think of one unless it was applied to a class which overloaded stream insertion operator in a non-conventional way.
Jamie Cook
+1  A: 

What about using type traits for serializing different types to the stream like this:

template<typename T>
struct Traits {
  static inline bool ToStream(std::ostringstream& o, const T& x) {
    return o << x;
  }
};

template<typename T1, typename T2>
struct Traits<std::pair<T1, T2> > {
  static inline bool ToStream(std::ostringstream& o, const std::pair<T1, T2>& x) {
    return o << "[" << x.first << "," << x.second << "]";
  }
};

template<typename T>
inline std::string ToString(const T& x)
{
  std::ostringstream o;
  if (!Traits<T>::ToStream(o, x))
    return "Error";
  return o.str();
}

Note: "template<>" from the specialization part is optional, the code compiles fine without it. You can further add methods in the traits for the exception message.

Radu
The 'template<>' line is actually not allowed (neither gcc4.3 nor Comeau online accept it, for example)
James Hopkin
It worked on gcc4.0.1. Removed it from the code though since it's not required.
Radu
What is the benefit of this over simple method overloading as litb suggested?
Jamie Cook
In this particular example, probably no benefit, just another way to do it. Traits would be useful if you had a more complex method or if you needed more customizations based on the template type.Another simple way to solve your example would be define the << operator for the missing types and just use the initial template function.
Radu