Let's say I have a std::any
object which may or may not contain a pointer to some derived class of a given base class B
. Is there any way I can do something that:
- Returns a
B *
, if thestd::any
object holds something convertible toB *
, or - Throws an exception if not?
It seems like dynamic_cast
and std::any_cast
each provide one half of this functionality, but I don't see any way of putting the two together.
I'm aware that I can make this work in various ways that involve explicitly enumerating every type convertible to B *
, but that's the mother of all DRY violations.
Sample use case:
std::vector<std::any> setupTools(const std::string & confFile)
{
std::vector<std::any> myTools;
auto conf = parse(confFile);
for(std::string & wrenchInfo : conf["Wrenches"])
{
Wrench::setup(myTools, wrenchInfo);
}
for(std::string & hammerInfo : conf["Hammers"])
{
Hammer::setup(myTools, hammerInfo);
}
// 25 more kinds of tools
}
Factory1::init(const std::vector<std::any> & tools)
{
m_wrench = any_get<Wrench *>(tools);
m_hammer = any_get<Hammer *>(tools);
m_saw = any_get<Saw *>(tools);
}
Factory2::init(const std::vector<std::any> & tools)
{
m_wrench = any_get<TorqueWrench *>(tools);
}
Factory3::init(const std::vector<std::any> & tools)
{
m_saw = any_get<CordlessReciprocatingSaw *>(tools);
}
I don't want to include a bunch of boilerplate code listing every single kind of saw in existence just so I can grab a saw -- any Saw
-- to use in Factory1
.
std::any
for this, and what you're trying to solve overall? This sounds like a very awkward problem and there's probably a better way around it – IrinairisB*
s into thestd::any
object, and not derived class pointers, then that solves the problem quite easily. – MontfortmyTools
are tools why not just have aTool
base class and makemyTools
astd::vector<std::unique_ptr<Tool>>
? – ShekinahmyTools
exists; why do you want to put what you claim are entirely dissimilar objects into it, then iterate over them to try to remember what you put there? – PancreatinCordlessReciprocatingSaw
then whether I'm iterating over all the tools or all the saws I'm still iterating over a bunch of stuff that is notCordlessReciprocatingSaw
s. – Hix