2015-10-12 71 views
1

我在尝试通过boost::any_cast引用强制检索boost::any实例后无法保持常量正确性。如何获得由boost :: any持有的数据的const引用?

我的代码:

MyMap paramMapToSet; 
MyMap& paramMap = &paramMapToSet; 
const MyMap& constParamMap = &paramMapToSet; 

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数据结构。

+1

为什么不通过编写更少的代码使问题看起来更简单?只写出那些在你心目中产生怀疑的代码,并将其余的代码作为“//做东西......”或类似的方式。 –

+1

@AnkitAcharya:因为这与我们问问题作者要做的事情相反吗? http://stackoverflow.com/help/mcve'//做东西'是毫无意义的,无益和烦人的。 –

+1

@LightnessRacesinOrbit我明白你的观点,但像上面这样简单的事情也可以用简单的代码来表示。这意味着更好地把一个小的测试代码,而不是一个庞大的项目代码 – CppNITR

回答

4

我只是猜测,但肯定...... hellip;

return any_cast<const T&>(data.at(path)); 
//    ^^^^^^ 

......不是吗?

+0

当然,它终于有效。我不知道你可以在那里写const。如果需要的话,我认为T在路上会自动获得const限定符。 – MatrixAndrew

+2

@AndrewVegvari:一个奇怪的假设,当它不编译,抱怨缺少'const',但没关系... –

相关问题