在我的项目中,我正在使用boost::any
并且boost::variant
详尽无遗。为此,在我之前的问题Generic function to convert boost::any to boost::variantboost::any
中设计了一个从to的通用转换例程。非常感谢帮助我的人。boost::variant
找到的解决方案对我来说没有任何问题,但有一些严重的缺点。完全模板化的解决方案产生的代码膨胀可能会令人望而却步,有时对于简单的转换是不必要的。(我没有提到编译时间。)
现在我有了让模板专业化为简单(非通用)转换工作的想法,但我发现必要的代码繁琐且容易输入错误。特别是,如果一个人必须一遍又一遍地完成这项任务。
下面的代码片段说明了这个问题。在典型应用程序中可能有多达 20 种或更多类型的图像!
#include <boost/preprocessor.hpp>
#include <boost/variant.hpp>
#include <boost/any.hpp>
#include <boost/optional.hpp>
#include <iostream>
template<typename VARIANT>
boost::optional<VARIANT> anyToVariant(const boost::any& any) {
boost::optional<VARIANT> ret;
// General implementation omitted.
// The implementation is lengthy and produces an enormous code bloat. In some cases it is the best solution.
return ret;
}
// Specialized Template reduces code bloat. But is error-prone to type write for every new variant type.
template<>
boost::optional <boost::variant<int, double, std::string>> anyToVariant(const boost::any& any) {
boost::optional<boost::variant<int, double, std::string>> ret;
if (any.type() == typeid(int)) {
ret = boost::any_cast<int>(any);
}
if (any.type() == typeid(double)) {
ret = boost::any_cast<double>(any);
}
if (any.type() == typeid(std::string)) {
ret = boost::any_cast<std::string>(any);
}
return ret;
}
// Should be implemented with boost preprocessor
#define BOOST_ANY_TO_VARIANT(TypeList)
// Better would be a macro like this
BOOST_ANY_TO_VARIANT(int, double, std::string); // Create the above template specialization
int main() {
boost::variant<int, double, std::string> v;
boost::any x = 4;
v=*anyToVariant<boost::variant<int, double, std::string>>(x);
}
更好的解决方案当然是宏,但不幸的是我无法使用boost-preprocessor
. 我仍然缺乏技能,但我相信这是可以做到的。
有经验的人可以boost-preprocessor
帮我解决我的问题吗?
我能想象的最好的解决方案是如下的宏:
#define BOOST_ANY_TO_VARIANT(VariantType) \
// Magic?
typedef boost::variant<int, std::string, double> MyVariant;
BOOST_ANY_TO_VARIANT(MyVariant)
但我怀疑这个解决方案是否可行。