我在嘗試通過boost::any_cast
引用強制檢索boost::any
實例後無法保持常量正確性。如何獲得由boost :: any持有的數據的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: error: C2440: 'return' : cannot convert from 'const nonref' to 'A &' Conversion loses qualifiers
哪裏線284看起來是這樣的:
實施:
// 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;
};
return any_cast<const nonref &>(const_cast<any &>(operand));
它是從下方的行叫
你可能會認爲MyMap提供了無用的包裝功能,它已經出現在盒子裏,howeve真正的實現有get/set方法,它們在內部的std :: map中自動創建嵌套的地圖,提供了一個很酷的靈活的DOM數據結構。
爲什麼不通過編寫更少的代碼使問題看起來更簡單?只寫出那些在你心目中產生懷疑的代碼,並將其餘的代碼作爲「//做東西......」或類似的方式。 –
@AnkitAcharya:因爲這與我們問問題作者要做的事情相反嗎? http://stackoverflow.com/help/mcve'//做東西'是毫無意義的,無益和煩人的。 –
@LightnessRacesinOrbit我明白你的觀點,但像上面這樣簡單的事情也可以用簡單的代碼來表示。這意味着更好地把一個小的測試代碼,而不是一個龐大的項目代碼 – CppNITR