如另一个问题所述,
How do I fix âambiguous overloadâ error when overloading operator<< (templated)?
,定义时
operator<<(std::ostream&, T)
对所有人
T
,则为现有
operator<<
os << n << ", ";
^-- recursively calls itself? or calls the overload provided by the Standard Library?
SFINAE
以确保只为iterable类型定义重载。因为
range-based for loop
基于
begin
end
,我们可以用它来区分什么是
Iterable
:
template<class Iterable, class = std::void_t<decltype(begin(std::declval<Iterable>()))>>
std::ostream& operator<<(std::ostream& os, Iterable const& iterable)
{
for (auto const& n : iterable)
os << n << ", ";
return os;
}
demo
)
std::cout << data
std::cout << '\n'
调用内建重载,因为对的替换失败
Iterable = char
:
begin(char)
未定义。