具有类型规范的boost :: make_optional [英] boost::make_optional with type specification
问题描述
与模板规范一起使用时, boost :: make_optional()行为令我感到困惑.
I'm puzzled about the boost::make_optional() behavior when used with the template specification.
尤其是,我仍然不清楚为什么会这样:
In particular, it's still unclear to me why this:
int pizza = 5;
boost::optional<int> pizza_opt = boost::make_optional<int>(pizza)
引发编译错误无法将类型为'int&&'的右值引用绑定到类型为'int'的左值;而这:
int foo(int bar)
{ return bar; }
boost::optional<int> pizza_opt = boost::make_optional<int>(foo(pizza))
工作正常.
我已经从这得知,使用没有多大意义boost :: make_optional 指定类型,但是我正在阅读一些使用此结构的代码.
I already know from this that it does not make much sense to use boost::make_optional specifying the type, but I'm reading some code which does use of this structure.
谢谢!
推荐答案
boost :: make_optional
的模板参数未在optional内部精确定义类型.
Template parameter of boost::make_optional
doesn't define exactly type inside optional.
此模板参数负责完美转发,这是简单的最小示例重现问题:
This template parameter is responsible for perfect forwarding, here is simple minimal example reproducing issue:
#include <iostream>
template<typename T>
void bar(T&& x)
{
std::cout << __PRETTY_FUNCTION__ << " "
<< std::forward<T>(x) << '\n';
}
int foo(int x)
{
return x + 1;
}
int main()
{
int pizza = 5;
bar(pizza);
bar<int>(foo(pizza));
// bar<int>(pizza); // same error
return 0;
}
实时演示.
因此,推论完成后,对于L值,T是 int&
;对于r值,T是 int
.
So when deduction is done T is int&
for l-values and int
for r-values.
当您传递变量时,您传递的是左值.
When you pass variable you passing l-value.
指定类型时,您将强制参数为 int&&
,该参数与 int&
不匹配.
When you specified type you are forcing argument to be int &&
which do not match to int&
.
这篇关于具有类型规范的boost :: make_optional的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!