在尝试通过引用强制转换检索boost::any
实例后,我无法维护 const 的正确性。boost::any_cast
我的代码:
MyMap paramMapToSet;
MyMap& paramMap = ¶mMapToSet;
const MyMap& constParamMap = ¶mMapToSet;
A hoe;
paramMap.set(hoe, "structA");
// this works
A& hoeRef = paramMap.getByRef<A>("structA");
hoeRef.myInt = 101;
cout << paramMap.get<A>("structA").myInt << endl; // prints 101
// as well as this:
hoe = constParamMap.get<A>("structA");
cout << hoe.myInt << endl;
// and this:
const A& constHoeRef = paramMap.getByRef<A>("structA");
cout << constHoeRef.myInt << endl;
// however this doesn't work, why?? (error message below)
const A& constHoeRef = constParamMap.getByRef<A>("structA");
cout << constHoeRef.myInt << endl;
对于为什么只有最后一个版本会产生错误,我也有点困惑。我收到的错误消息是这样的:
C:...\boost_1_58_0\boost\any.hpp:284: error: C2440: 'return' : cannot convert from 'const nonref' to 'A &' 转换丢失限定符
第 284 行如下所示:
return any_cast<const nonref &>(const_cast<any &>(operand));
它是从下面的一行调用的:
实施:
// a testing class:
struct A{
int myInt;
A() = default;
A(const A& other) : myInt(other.myInt)
{ cout << "Class A is being copied" << endl; }
};
// any-map implementation
class MyMap{
public:
template<typename T>
T get(const std::string& path) const
{
return any_cast<T>(data.at(path));
}
template<typename T>
const T& getByRef(const std::string& path) const
{
return any_cast<T&>(data.at(path)); // compiler originates the error from here
}
template<typename T>
T& getByRef(const std::string& path)
{
return any_cast<T&>(data.at(path));
}
template<typename T>
void set(T val, const std::string& path)
{
data[path] = val;
}
private:
std::map<std::string, boost::any> data;
};
您可能会认为 MyMap 提供了开箱即用的无用包装功能,但真正的实现具有 get/set 方法,可在内部 std::map 内自动创建嵌套映射,提供酷炫灵活的 DOM 类数据结构。