c++ - Boost::任何对存储值的引用都无法编译

标签 c++ boost boost-any

我正在尝试编写一个通用配置类来保存这样的参数(大大简化):

class Parameter
{
public:
   Parameter(boost::any value, bool isRequired) 
     : value(value), isRequired(isRequired) {}
   bool isSet;
   bool isRequired;
   boost::any value;
};

class ParameterGroup
{
public:
   map<std::string, Parameter> table;
   // references for chaining
   ParameterGroup& add_parameter_group(const string &token, const bool isRequired);
   ParameterGroup& add_parameter(const string &token, const bool isRequired);

   template<typename T>
   T& get_parameter(const string &token);
};

问题出在 add_parameter_group 函数中:

ParameterGroup& ParameterGroup::add_parameter_group(const string &token, 
                                                    const bool &isRequired)
{
   table[token] = Parameter(ParameterGroup(), isRequired);
   return boost::any_cast<ParameterGroup>(table[token].value);
}

返回无法编译并显示消息

error: invalid initialization of non-const reference of type ParameterGroup& from an 
       rvalue of type ParameterGroup

我不明白为什么。根据 boost::any_cast 文档:

If passed a pointer, it returns a similarly qualified pointer to the value content if successful, otherwise null is returned. If T is ValueType, it returns a copy of the held value, otherwise, if T is a reference to (possibly const qualified) ValueType, it returns a reference to the held value.

为什么这无法像它应该的那样返回引用?

最佳答案

T不是引用类型,而是ValueType,所以根据你引用的文档,你得到一个值。

然后,您尝试将此[临时]值绑定(bind)到非const的引用。

您尝试激活的子句是:

if T is a reference to (possibly const qualified) ValueType, it returns a reference to the held value.

那么,让我们将 T 设为对 ValueType 的引用:

boost::any_cast<ParameterGroup&>(table[token].value);
//              ^^^^^^^^^^^^^^^
//              |------------||
//                ValueType (ref)
//              |-------------|
//                     T

现在您将获得对所保存值的引用,它将很好地绑定(bind)到返回类型。

关于c++ - Boost::任何对存储值的引用都无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20380079/

相关文章:

c++ - 是否可以将 boost::any 或 boost::variant 与 boost::pool 一起使用?

c++ - 提振 spirit ,提振任何意想不到的结果

c++ - 在 QHBoxLayout 中将小部件添加到屏幕外以便稍后显示

c++ - GCC 和 Clang 是否优化逐字段结构复制?

c++ - 在不存在的对象上调用成员函数可以正常工作,c++

c++ - 如何用 "-pthread"而不是 "-mthread"编译 boost_thread?

c++ - 如何使用boost::unit_test 编写脚本来执行自动测试?

c++ - 将 boost::intrusive_ptr 与嵌套类一起使用

c++ - 使用函数 <void (boost::any)> 的事件系统是个好主意?

c++ - 有没有一种方法可以避免在std::variant类成员中为所有类型编写构造函数?