Data type for std::string or std::endl

223 Views Asked by At

I have the following function template:

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <iostream>
#include <string>
#include <vector>

template <typename Streamable>
void printall(std::vector<Streamable>& items, std::string sep = "\n")
{
    for (Streamable item : items)
        std::cout << item << sep;
}

#endif

Now I'd like to set the default value of septo std::endl instead, which is a function, not a std::string. But I'd also like the user to be able to pass in a std::string. How must I specify the argument sep's type to accept both, an arbitrary std::string as well as std::endl?

1

There are 1 best solutions below

0
On BEST ANSWER

If you want the default value for the second parameter to be std::endl, then you can simply add an overload that takes only one parameter, and don't provide a default for the string overload. This will give you the overload set that you desire.

template <typename Streamable>
void printall(std::vector<Streamable>const & items)  // gets called when second 
                                                     // argument is not passed in
{
    for (Streamable const & item : items)
        std::cout << item << std::endl;
}

template <typename Streamable>
void printall(std::vector<Streamable> const & items, std::string const & sep)
{
    for (Streamable const & item : items)
        std::cout << item << sep;
}