- 论坛徽章:
- 1
|
关于 boost::any, 谁能帮我解答这个问题
归根结底,算了,不归根结底了,一步步来看一下.
首先:any_cast<T>;(any_vector[index]); 它调用的是:- template<typename ValueType>;
- ValueType any_cast(const any & operand)
- {
- const ValueType * result = any_cast<ValueType>;(&operand);
- if(!result)
- boost::throw_exception(bad_any_cast());
- return *result;
- }
复制代码 而此函数转而调用的是:- template<typename ValueType>;
- const ValueType * any_cast(const any * operand)
- {
- return any_cast<ValueType>;(const_cast<any *>;(operand));
- }
复制代码 而此函数又转而调用:- template<typename ValueType>;
- ValueType * any_cast(any * operand)
- {
- return operand && operand->;type() == typeid(ValueType)
- ? &static_cast<any::holder<ValueType>; *>;(operand->;content)->;held
- : 0;
- }
复制代码 看到了吗?返回值是从static_cast转换而来的临时对象的地址.你应该知道static_cast会构造临时对象吧?
还有一个问题就是,你的get是返回const类型而调用的成员函数不是const的.所以把test声明成const.或者你直接返回值也行.而不是引用:如下:
- #include <vector>;
- #include <string>;
- #include <boost/any.hpp>;
- using namespace std;
- using namespace boost;
- class my
- {
- public:
- void test()const {}
- };
- vector<any>; any_vector;
- template<typename T>; const T get(int index)
- {
- return any_cast<T>;(any_vector[index]);
- }
- int main()
- {
- any_vector.push_back(10);
- any_vector.push_back(string("hello"));
- any_vector.push_back(my());
- any_vector[0]=string("nana");
- get<my>;(2).test();
- return 0;
- }
复制代码 |
|