我正在尝试编写一个包含这样的参数的通用配置类(大大简化了):
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 的引用,它返回对保存值的引用。
为什么这没有返回看起来应该的引用?