通用功能转换的boost ::任何提振::变种 [英] Generic function to convert boost::any to boost::variant
问题描述
假设你有一个的boost ::任何
对象和的boost ::变种
对象。
Assume that you have a boost::any
object and a boost::variant
object.
我在寻找一个泛型函数转换
,带有一个模板参数T是一个专门的的boost ::变种
例如: 的boost ::变种< INT,标准::字符串>
和神奇的的boost ::任何
转换为之一可用的类型给定的的boost ::变种
。
I'm looking for a generic function convert
, that takes a template parameter T being a specialized boost::variant
e.g. boost::variant<int, std::string>
and magically converts the boost::any
to one of the available types of the given boost::variant
.
template<T>
T convert(const boost::any& any) {
// Some generic conversion code here or throw exception if conversion is not possible!
}
int main(int argc, char** args) {
typedef boost::variant<int, std::string> TVar;
boost::any any="Hello World";
TVar variant=convert<TVar>(any);
// variant contains "Hello World"
return 0;
}
我不知道是否有可能写这样的功能,或者它可能会因为某些原因不可能?
I'm wondering if it is possible to write such a function or if it might be impossible for some reason?
推荐答案
让我们附上所有code的结构由变量类型模板
Let's enclose all code in struct templated by variant type
template<class VAR>
struct ExtractorGenerator
{
using Extractor = std::function<boost::optional<VAR>(boost::any const &)>;
std::vector<Extractor> extractors;
template<class T>
static boost::optional<VAR> tryCast(boost::any const & arg);
template<class T>
void operator()(T);
};
您可以轻松地编写一个函数,给定类型的尝试转换的boost ::任何这种类型的变种
You can easily write a function that for given type tries to convert boost::any to variant of this type
template<class VAR>
template<class T>
boost::optional<VAR> ExtractorGenerator<VAR>::tryCast(boost::any const & arg)
{
T const * val = boost::any_cast<T>(&arg);
return val == nullptr ? boost::none : boost::make_optional(VAR{*val});
}
现在使用boost :: MPL可以通过所有变量类型迭代生成每个变量的类型函数
Now using boost::mpl you can iterate through all variant types to generate function for each variant's type
template<class VAR>
template<class T> void ExtractorGenerator<VAR>::operator()(T)
{
extractors.push_back(Extractor::tryCast<T>);
}
typedef boost::variant<int, std::string, char> MyVariant;
ExtractorGenerator<MyVariant> generator;
boost::mpl::for_each<MyVariant::types>(boost::ref(generator));
和现在你只申请创建的所有功能:
And now you just apply all created functions:
std::vector<MyVariant> extractedVals;
for (auto fun : extractor.extractors)
{
boost::optional<MyVariant> extracted = fun(val);
if (extracted)
extractedVals.push_back(extracted.get());
}
这篇关于通用功能转换的boost ::任何提振::变种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!