运算符重载意外地破坏了函数
添加重载函数时,会调用 operator<<()
的不明确重载。
template <typename Container> ostream& operator<<(ostream& os, const Container& c)
{
copy(c.begin(), c.end(), ostream_iterator<typename Container::value_type>(os, " "));
return os;
}
当我在使用 <<
的函数上
void print_list(const list<int>& list_int)
{
for (list<int>::const_iterator it = list_int.begin(); it != list_int.end(); it++) cout << *it << " ";
}
Ambiguous overload for operator<<()
is called when I add the overload function below
template <typename Container> ostream& operator<<(ostream& os, const Container& c)
{
copy(c.begin(), c.end(), ostream_iterator<typename Container::value_type>(os, " "));
return os;
}
the error is called on this function where it uses the <<
.
void print_list(const list<int>& list_int)
{
for (list<int>::const_iterator it = list_int.begin(); it != list_int.end(); it++) cout << *it << " ";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(仅供参考,如果其他人正在寻找: http://ideone.com/YlX7q )
您对运算符的定义< <可以实例化为
::operator<<(std::ostream&, const int&)
;这对于std::operator<<(std::ostream&, int)
来说是不明确的。调用类型 Container 的名称并不意味着它是一个容器;而是意味着它是一个容器。重载决策在定义实例化之前完成。(For reference, if anyone else is looking: http://ideone.com/YlX7q )
Your definition of operator<< can be instantiated as
::operator<<<int>(std::ostream&, const int&)
; this is ambigious withstd::operator<<(std::ostream&, int)
. Calling the name of the type Container doesn't mean it is a container; overload resolution is done before the definition is instantiated.是的,这当然行不通。
您正在引入模板化重载,并且当您使用该运算符时,编译器不再知道要使用什么。
你根本不能那样做。
你可以做这样的事情:
但你不能这样做
Yes of course this cannot work.
You are introducing a templated overload, and the compiler don't know anymore what to use when you use that operator.
Simply you cannot do that.
You can do something like this:
but you cannot do