为什么这段代码可以编译?
std::shared_ptr<const int> Bar()
{
return std::make_shared<int>(123);
}
但这不...
boost::optional<const int> Foo()
{
return boost::optional<int>(123);
}
我收到以下错误:
could not convert 'boost::optional<int>(123)' from 'optional<int>' to 'optional<const int>'
使用 gcc 6.3.0 和 boost 1.65.1。
最佳答案
boost::optional
的转换构造函数被标记为显式。因此,您不能从 boost::optional<T>
执行隐式转换至 boost::optional<U>
.您可以执行显式转换:
boost::optional<const int> Foo()
{
return boost::optional<const int>(boost::optional<int>(123));
}
值得注意的是 std::optional
(这是在 C++17 中添加的,并且基于 boost 的版本)具有转换构造函数,这些构造函数只有在包含的类型不可隐式转换时才是显式的。因此你的Foo
功能将按原样与 std::optional
一起使用.
关于c++ - 从非 const 到 const 模板参数的隐式转换在 boost::optional 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47837956/