我通常对这类任务使用模板专业化。我有一个模板函数,可以从变体类型转换为 C++ 类型,如下所示:
template <typename T>
T variantToCpp(const Variant&);
template <>
int variantToCpp<int>(const Variant& v)
{
// Check that v really contains an int, if not, you can silently fail or throw an exception
// Get and return the int
}
template <>
std::wstring variantToCpp<std::wstring>(const Variant& v)
{
// Check that v really contains a string, if not, you can silently fail or throw an exception
// Get and return the string
}
// etc. for each C++ type
// Usage
int i = variantToCpp<int>(someVariantIGotViaCOM);
通过这种方式,您可以获得从 Variant 到 C++ 类型的恒定时间转换。另请注意,默认模板化函数没有主体 - 如果有人尝试对非专业类型使用转换,它将导致链接器错误(在大多数编译器上)。
同样,您可以进行从 C++ 类型到 Variant 的转换:
template <typename T>
Variant cppToVariant(T);
template <>
Variant cppToVariant<int>(int val)
{
// Convert to variant and return it
}
// etc. for each type
// Usage:
int i = 10;
Variant var = cppToVariant(i); // You don't even need to explicitly specify the type here, the compiler deduces it
如果您坚持使用映射和大量 ifs 进行这种转换,则可以使用 void* 指针,只需使用指向类型的指针对其进行初始化:
int *myInteger = new int; *myInteger = 42;
double *myDouble = new double; *myDouble = 42;
typemap.insert( m_typepair(VT_INTEGER, myInteger));
typemap.insert( m_typepair(VT_DBL, myDouble));
// Don't forget to free them when you clear the map
如果您对上述任何解决方案都不满意,boost::any可能值得一看。