gpt4 book ai didi

c++ - 如何为 boost::tuple 编写一个 `<<` 运算符?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:56 29 4
gpt4 key购买 nike

在下面的示例代码中,它表明可以从第一个模板参数隐式创建 boost::tuple。因此,我无法写 <<运算符,因为它变得模棱两可。

我也不明白为什么ostringstream& << float也是模棱两可的。这没有任何隐式构造。为什么这也会产生模棱两可的错误?

#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <sstream>
#include <string>

using namespace std;

class Myclass
{
};

typedef boost::tuple<int,float,Myclass> Mytuple;

ostringstream& operator<<(ostringstream& os_, Mytuple tuple_)
{
float f = tuple_.get<1>();
//os_ << (int)tuple_.get<0>(); // Error because int is implicitly converted into Mytuple. WHYY?
//os_ << tuple_.get<1>(); // No Clue Why this is ambiguous.
//os_ << tuple_.get<2>(); // Error because no matching operator. Fine.
return os_;
}

int main()
{
Mytuple t1;
t1 = 3; // Working because int is implicitly converted into Mytuple!! WHY?
//t1 = 3.0f; // Error because no matching constructor. Fine.
return 0;
}

错误信息:

tupleTest2.C:18: error: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:

最佳答案

问题不在于元组,而在于您的运算符。这很好用:

ostream& operator<<(ostream& os_, Mytuple tuple_)
{
os_ << tuple_.get<0>(); // Error because int is implicitly converted into Mytuple. WHYY?
os_ << tuple_.get<1>(); // No Clue Why this is ambiguous.
//os_ << tuple_.get<2>(); // Error because no matching operator. Fine.
return os_;
}

问题是 ostringstream 继承了 operator<<来自 ostream,它有这个签名:ostringstream& operator<<(ostringstream& os_, Mytuple tuple_)被允许。然后是

ostream& operator<<(ostream& os, T t)

(用 C++ 中的所有可用类型更改 T,请参阅 operator<< reference page

编辑

这是一个简化的例子(没有元组):

ostringstream& operator<<(ostringstream& os_, Mytuple tuple_)
{
const int i = tuple_.get<0>();
os_ << i; // error in this line
return os_;
}

现在的错误是:

dfg.cpp: In function ‘std::ostringstream& operator<<(std::ostringstream&, Mytuple)’:
dfg.cpp:18: error: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
/usr/lib/gcc/i386-redhat-linux/4.3.0/../../../../include/c++/4.3.0/bits/ostream.tcc:111: note: candidate 1: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
dfg.cpp:14: note: candidate 2: std::ostringstream& operator<<(std::ostringstream&, Mytuple)

上面的错误消息说:无法在两个运算符之间进行选择 operator<<(ostream&,...)operator<<(ostringstream&,...). This also raises another question : why on earth do you need运算符<<(ostringstream&,...)`?

关于c++ - 如何为 boost::tuple 编写一个 `<<` 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7593710/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com