2011-06-06 36 views
2

我試圖使用多個模板將數據傳遞到一個函數,但只使用第一個模板參數作爲過濾器。事情是這樣的:未指定的模板參數

template <typename A, typename B> 
class Component { 

}; 

template <typename A> 
class Context { 
    public: 
     void add(Component<A, void *> comp) { 
     } 
} 

typedef struct Foo { int x; } Foo; 
typedef struct Bar { int y; } Bar; 
Context<Foo> *context = new Context<Foo>(); 
Component<Foo, Bar> *comp = new Component<Foo, Bar>(); 
context->add(comp); // error 

但是,編譯器抱怨說,它不能轉換Component<Foo, Bar>Component<Foo, void *>。有沒有辦法做到這一點?

回答

1

我想你可能需要做的是更改'添加'方法的簽名:

template <typename A> 
class Context 
{ 
public: 
    template<class B> 
    void add(Component<A, B> comp) 
    {   
    } 
}; 

但是,我不知道你的問題的細節,所以這只是一個猜測。

0

是,添加一個轉換拷貝構造函數你Component

template<class U, class V> 
Component(Component<U,V> const& other){ 
    // ... 
}; 

但仍然refineable與適當的enable_if SFINAE後衛:

// <tr1/type_traits> for C++03 
#include <type_traits> // for C++0x 

template<class T, class U> 
struct can_convert{ 
    // std::tr1::... for C++03 
    static bool const value = 
     std::is_same<T,U>::value || std::is_convertible<T,U>::value; 
}; 

template<class C1, class C2> 
struct ice_and{ 
    static bool const value = C1::value && C2::value; 
} 

// define for clarity and brevity 
#define IF_CAN_CONVERT(A,B,U,V) \ 
    typename std::enable_if<ice_and<can_convert<A,U>,can_convert<B,V> > >::type* = 0 

template<class U, class V> 
Component(Component<U,V> const& other, IF_CAN_CONVERT(A,B,U,V)){ 
    // ... 
}; 
0

我想用多個模板傳遞數據到一個函數,但只使用第一個模板參數作爲過濾器。 [...]但編譯器抱怨說它不能將組件轉換成組件。有沒有辦法做到這一點?

那麼,你的過濾器正在對不對:你add功能將只匹配一個組件,其第二個模板參數是void*,而你提供Bar。你還能期待什麼?如果您希望它也處理其他「第二參數」,請移除篩選器,提供回溯函數以匹配或進行某種轉換。