2

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

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文档:

如果传递了一个指针,如果成功则返回一个类似限定的指向值内容的指针,否则返回 null。如果 T 是 ValueType,它返回一个保存值的副本,否则,如果 T 是对(可能是 const 限定的)ValueType 的引用,它返回对保存值的引用。

为什么这没有返回看起来应该的引用?

4

2 回答 2

3

T不是引用类型,但是ValueType,因此根据您引用的文档,您会得到一个值。

然后,您尝试将此 [临时] 值绑定到 ref-to-non- const

您尝试激活的子句是:

ifT是对 (可能是 const 限定的)ValueType的引用,它返回对所持有值的引用。

所以,让我们T参考一下ValueType

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

现在您将获得对所持有值的引用,该值将很好地绑定到返回类型。

于 2013-12-04T16:11:18.827 回答
1

直接取自boost::any 标头

  template<typename T> T any_cast(any &);
  template<typename T> T any_cast(const any &);
  template<typename ValueType> const ValueType * any_cast(const any *);
  template<typename ValueType> ValueType * any_cast(any *);

因此,当您请求一个值时,您会看到 boost::any_cast 返回一个副本,这就是您不能返回引用的原因。所以尝试使用 any_cast 投射参考

于 2013-12-04T16:11:08.573 回答