2

假设我有一个功能:pair<int, int> foo()我想直接输出 this 的两个元素而不使用临时。

有没有办法可以输出这个,或者将它转换成字符串输出?我可以tie用来做这个吗?

这是我正在尝试对临时做的事情:

const auto temporary = foo();

cout << temporary.first << ' ' << temporary.second << endl;
4

3 回答 3

3

在 c++17 标准中,您可以使用结构化绑定声明

std::pair<int, int> get_pair()
{
    return {10, 20};
}

int main()
{
    auto [x, y] = get_pair();
    std::cout << x << " " << y << std::endl;
    return 0;
}
于 2018-12-06T21:59:29.173 回答
2

不,你不能在不使用非临时函数的情况下编写该函数。如果你真的需要,你可能应该改变你的代码结构。从技术上讲,您也可以使用全局变量(尽管我强烈不推荐这样做)。我认为tie这也不适用于您想要的。

于 2018-12-06T20:59:04.513 回答
2

您可以创建一个包装 的小类std::pair,并启用输出流以通过以下方式打印它operator<<

template<typename PairT>
struct printable {
    const PairT& p;
    printable(const PairT& p)
        :    p{p}
    {}
};

template<typename CharT, typename PairT>
std::basic_ostream<CharT>& operator<<(std::basic_ostream<CharT>& out, const printable<PairT>& pair) {
    out << pair.p.first << ' ' << pair.p.second;
    return out;
}

然后你可以像这样使用它:

auto foo() {
    return std::pair<int, int>(1, 2);
}

int main() {
    std::cout << printable(foo());
}

活生生的例子


当然,您也可以直接启用打印std::pair...

template<typename CharT, typename A, typename B>
std::basic_ostream<CharT>& operator<<(std::basic_ostream<CharT>& out, const std::pair<A, B>& pair) {
    out << pair.first << ' ' << pair.second;
    return out;
}

// (...)

std::cout << foo(); // And this would work just fine

...但我并不真正推荐它,特别是在标题上,因为您基本上会改变标准类型的行为,而您的同事(或您自己,将来)可能会对此感到困惑。

于 2018-12-06T21:16:05.613 回答