2010-09-01 301 views
0

我正在爲COM對象編寫COM包裝器,該對象從客戶端發送不同類型的值,並且希望將這些類型映射到它們的實際C++類型,例如VT_BSTR到一個wstring等使用映射將COM VARIANT類型映射到實際類型

我想定義一個COM Variant類型的枚舉,然後使用一個映射將該枚舉作爲鍵和包含檢索值的實際類型,但是我遇到了問題,我似乎無法找到一個全球性的類型放在我的地圖上,我可以投到一個字符串或雙或任何交給我放在地圖上。

也許我對如何做到這一點的想法是完全錯誤的,請指教?

我在想一個空指針的,但它似乎編譯器不喜歡我的石膏:

(例如)

enum Type 
    { 
     VT_INTEGER=0, 
     VT_DBL=1 

    }; 


    map<Type, void*> typemap; 
    typedef pair<Type, void*> m_typepair; 
    typemap.insert(m_typepair(VT_INTEGER, 0)); 
    typemap.insert(m_typepair(VT_DBL, (double)2.5)); // it does not like this cast 

    map<Type, void*>::iterator m_typeiter; 

遍歷這個地圖很可能需要在switch語句中找到正確的類型,我不確定是否有更好的方法?

回答

0

我通常對這類任務使用模板專業化。我有一個模板功能,從一個變量類型轉換爲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); 

這樣,你從一個變到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可能是值得考慮的。

1

不知道你要做什麼,它肯定聽起來不對。您從客戶端獲得的VARIANT需要轉換爲您知道如何處理的類型。這很容易,只需調用VariantToXxxx()函數即可。例如,如果要獲取字符串,請使用VariantToString()。

有幾個C++包裝類已經可用,使這更容易。 _variant_t,CComVariant,COleVariant。他們都做同樣的事情,只是不同的#include文件。 _variant_t是一個很好的選擇,因爲它不會將您與MFC或ATL綁定。除非你已經在使用它們。他們的ChangeType()方法進行轉換。內存管理是自動的。

0

您是否知道_variant_t?你可能正在重新發明輪子。它有所有相關的constrcutors和重載的任務。即_variant_t var = 0.0按預期工作(VT_R8