views:

44

answers:

1

I'm trying to write a function to "stringify" parameters for logging purpose. For example, I'd like to write something like this:

vector<string> queries; 
set<uint_8> filters;
LOG(INFO) << stringify<vector, string>(queries);
LOG(INFO) << stringify<set, uint_8>(filters);

Here is the function template I wrote:

template <typename containerType, typename elemType>
string _stringify(const string name, const containerType<elemType> &elems) {
    ostringstream os;
    os << name << ": [";
    BOOST_FOREACH(elemType elem, elems) {
        os << elem << ",";    
    }
    os << "]";
    return os.str();
} 

Here is the error message I got: error: ‘containerType’ is not a template

Thanks, Alex

+5  A: 

You need to use a template template parameter, e.g.,

template <template <typename> class containerType, typename elemType>
string _stringify(const string name, const containerType<elemType>& elems)

Note that if you are expecting to use this with standard library containers, most of them have several template parameters (the sequence containers, for example, have two: one for the value type and one for the allocator type).

It is probably easier (and better) to use the value_type typedef that all containers have. For example,

template <typename ContainerT> 
void f(const ContainerT& c)
{
    typedef typename ContainerT::value_type ElementT;  
    // Use ContainerT and ElementT
}
James McNellis
+1 for `value_type`.
Billy ONeal
Thanks James, that's a beautiful answer. Much cleaner. Thanks.
Alex Dong