尝试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:'return':无法从'const nonref'转换为'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。
我只是在猜测,但是,肯定是……
return any_cast<const T&>(data.at(path));
// ^^^^^^
…不?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句