참조 캐스팅을 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 : 오류 : 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이 이미 즉시 사용할 수있는 쓸모없는 래핑 기능을 제공한다고 생각할 수 있지만 실제 구현에는 내부 std :: map 내부에 중첩 된 맵을 자동으로 생성하는 get / set 메서드가있어 데이터 구조와 같은 멋진 유연한 DOM을 제공합니다.
추측이긴하지만 확실히 ...
return any_cast<const T&>(data.at(path));
// ^^^^^^
…아니?
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다