Prev: why are missing return statements from non-void functions not a compilation error
Next: why are missing return statements from non-void functions not a compilation error
From: 狂怒之人 on 26 Jul 2010 23:46 For example: int f(boost::any pi) { if(int i = boost::any_cast<const int*>(pi)) { return i; } } int main() { int a = 1; f(boost::any(&a));//throw an bad_any_cast exception } Boost::any can not handle derived-to-base cast too, so It seems boost::any is not appropriate to be a function parameter. Is there any solution to this problem? -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Daniel Krügler on 27 Jul 2010 06:13
On 27 Jul., 16:46, 狂怒之人 <shendia...(a)gmail.com> wrote: > For example: > > int f(boost::any pi) > { > if(int i = boost::any_cast<const int*>(pi)) > { > return i; > } > > } > > int main() > { > int a = 1; > f(boost::any(&a));//throw an bad_any_cast exception > } > > Boost::any can not handle derived-to-base cast too, so It seems > boost::any is not appropriate to be a function parameter. > Is there any solution to this problem? There does not exist a portable solution. boost::any uses the built-in std::type_info structure and that allows only to check for equality in a meaningful way. Sure, std::type_info provides also an ordering function, but there is no way to follow any class hierarchy paths or to get cv information of pointees or referred types. Note that we might not want to stop at the level you are describing. You might ask: Why isn't it possible to read a wrapped int as a long? All these cases (including those mentioned above by yourself) cannot be solved with boost::any. It would require a much more advanced type information. I'm not aware of any proposal that suggests a concrete extended type information. I disagree with your argumentation that boost::any cannot be used as a function argument: With the same argument you could argue that void* is no feasible argument, but it often is. But I would say that such functions are typically used only internally, because otherwise you cannot ensure that the caller contract is satisfied (at least it would be ugly to specify: Typically a corresponding API should provide a way to test whether a given argument satisfies the criteria). It is possible to make boost::any easier to use at least concerning cv-qualifications of referenced objects and some basic (built-in) conversion cases, but it requires some mapping machinery behind that. Such mapping is not easy to realize for arbitrary class hierarchies, though. This would require at least some kind of dynamic is_base_of query function which we don't have at the moment. HTH & Greetings from Bremen, Daniel Krügler -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |