在尝试通过boost::any
引用转换检索boost::any_cast
实例后,我无法保持const正确性。
我的代码:
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:错误:C2440:&#39;返回&#39; :无法转换为&#39; const nonref&#39;到&#39; A&amp;&#39;转换失去限定符
第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,如数据结构
答案 0 :(得分:4)
我只是猜测,但肯定......
return any_cast<const T&>(data.at(path));
// ^^^^^^
...没有?