我有以下函数模板:
#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
现在我想将 sep
的默认值设置为 std::endl
,这是一个函数,而不是 std::string
。
但我也希望用户能够传入 std::string
。
我必须如何指定参数 sep
的类型以同时接受任意 std::string
和 std::endl
?
答案 0 :(得分: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;
}