1

我有以下功能模板:

#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

现在我想设置 to 的默认值,它是一个函数,sepstd::endl不是std::string. 但我也希望用户能够传入一个std::string. 我必须如何指定参数sep的类型以同时接受任意std::string的以及std::endl

4

1 回答 1

1

如果您希望第二个参数的默认值为std::endl,那么您可以简单地添加一个只接受一个参数的重载,并且不要为string重载提供默认值。这将为您提供所需的重载集。

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;
}
于 2021-04-19T02:46:56.910 回答