我正在尝试编写一个通用配置类来保存这样的参数(大大简化):
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/