gpt4 book ai didi

c++ - 是什么阻止了 Boost.Format 表单使用我的可选 int 流运算符重载?

转载 作者:行者123 更新时间:2023-11-28 01:26:36 24 4
gpt4 key购买 nike

我希望能够使用 std::optional<int>使用 Boost.Format。

#include <iostream>
#include <optional>
#include <boost/format.hpp>

struct SomeType
{
int x;
};

std::ostream& operator<<(std::ostream& os, const SomeType& t)
{
os << t.x;
return os;
}

std::ostream& operator<<(std::ostream& os, const std::optional<int>& t)
{
os << t.value_or(0);
return os;
}

void test()
{
SomeType t{42};
std::cout << (boost::format("%s") % t); //this is fine
std::optional<int> i = 42;
std::cout << (boost::format("%s") % i); //nope
}

上面的代码给出了以下编译器错误:

opt/compiler-explorer/libs/boost_1_68_0/boost/format/feed_args.hpp:99:12: error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'const std::optional<int>')
os << x ;
~~~^~~~

如果我简单地传递 i 就没有编译器错误直接到std::cout .

最佳答案

boost::format("%s") % i调用 operator<< .编译期间遵循名称查找规则以查找 operator<< .

对于 boost::format("%s") % t , 都是结构 SomeTypestd::ostream& operator<<(std::ostream& os, const SomeType& t)在全局命名空间中定义,使用 ADL,operator<<找到了。

对于 (boost::format("%s") % i) , std::optional在命名空间 std 中定义, 但对应 operator<<在全局命名空间中定义。通过使用 ADL,boost 将无法找到它。和

non-ADL lookup examines function declarations with external linkage that are visible from the template definition context,

所以编译器无法找到 operator<<你定义的。

解决方法:将 std::optional 包装在您自己的 ReferenceWrapper 中,然后在定义 ReferenceWrapper 的同一命名空间中为您的包装器定义插入器。

关于c++ - 是什么阻止了 Boost.Format 表单使用我的可选 int 流运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53477226/

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