为什么boost :: any禁止转发const&&?

时间:2014-07-23 12:22:04

标签: c++ c++11 boost

以下是相关代码:

// Perfect forwarding of ValueType
template<typename ValueType>
any(ValueType&& value
    , typename boost::disable_if<boost::is_same<any&, ValueType> >::type* = 0 // disable if value has type `any&`
    , typename boost::disable_if<boost::is_const<ValueType> >::type* = 0) // disable if value has type `const ValueType&&`
  : content(new holder< typename decay<ValueType>::type >(static_cast<ValueType&&>(value)))
{
}

据我所知,可以使用复制构造函数来构造const&amp;&amp ;.我使用boost 1.55.0。

1 个答案:

答案 0 :(得分:7)

这是https://svn.boost.org/trac/boost/ticket/9215的修正:

  

any构造函数调用const any&&

时的无限循环
#include <boost/any.hpp>
#include <string>
const boost::any getBoolVal()
{
    return false;
}
int main()
{
    boost::any vals[] = {1.0, std::string("1m"), getBoolVal()};
}

所以看起来意图是从转发构造函数中排除any const&&;它排除所有const rvalues的事实是副作用,无害,因为它们将由ValueType const&复制构造函数处理。

就我个人而言,我会选择

typename disable_if<is_same<any,
    typename remove_cv<typename remove_reference<ValueType>::type>::type>>::type

也能正确处理volatile rvalues - 而不是我见过的其中一个肉体。