【问题标题】:Including std::forward yield an error, but its omission compiles. Why?包括 std::forward 会产生一个错误,但它的省略编译。为什么?
【发布时间】:2017-10-09 16:23:11
【问题描述】:

我认为我从根本上误解了关于 std::forward 的一些东西。看看下面的代码——如果我包含 std::forward,它不会编译,但如果它被省略,它编译得很好。 std::forward 的意义不是它可以推断出是否需要推送 l 或 rvalue 吗?

#include "boost/optional.hpp"
#include "iostream"
template<typename T>
bool hasArg(const boost::optional<T>& opts)
{
    if (opts)
    {
        return true;
    }
    else
    {
        return false;
    }
}


template<typename T, typename ... Ts>
bool hasArg(const boost::optional<T> & opts,const boost::optional<Ts> & ... rest)
{
    if (opts) {
        //doesn't work: return hasArg<Ts...>(std::forward<Ts>(rest)...);
        //works: return hasArg<Ts...>(rest...);
        return hasArg<Ts...>(rest...);
    }
    else
    {
        return false;
    }
}


int main()
{
    const boost::optional<int> p = boost::optional<int>(5);
    const boost::optional<int> q = boost::optional<int>(6);
    std::cout << hasArg(p, q) << std::endl;
    return 0;
}

【问题讨论】:

  • 与您的问题无关,但您可能应该找到解释(不正确)#include "iostream" 和(正确)#include &lt;iostream&gt; 之间区别的地方。
  • std::forward 应该(仅?)与转发引用一起使用。即使您修复了语法,它在这里也不起作用。

标签: c++ c++11 stl c++14


【解决方案1】:

您甚至不需要转发参数,无论如何它们都是const&amp;

您将错误的类型传递给std::forward,这就是问题所在。 rest... 没有 Ts... 的类型,它们是 const boost::optional&lt;Ts&gt;&amp;...

所以你需要解决这个问题:

std::forward<const boost::optional<Ts>&>(rest)...

但如前所述,这根本没有意义,因为没有任何东西可以向前推进。 rest 不是转发参考。 (std::forward 用于保留值类别,但在这种情况下,它始终是相同的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 2023-03-22
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多