简体   繁体   中英

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

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 sep to 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 ?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM