2012-11-09 58 views
0

我使用MSVC 9.0和有此功能:模板類型推演失敗

class RecipientList 
{ 
public: 
    template<class T> 
    void fillMessageWithRecipients(typename boost::is_base_of<MsgContent, T>::type* msg); 
}; 

template< class T > 
void RecipientList::fillMessageWithRecipients(typename boost::is_base_of<MsgContent, T>::type* msg) 
{ 
// do stuff 
} 

我想模板類型推演到這裏工作,這樣我就可以這樣使用它:

class SomeMsg : public MsgContent {}; 

std::auto_ptr<SomeMsg> msg(new SomeMsg); 

RecipientList recipients; 
recipients.fillMessageWithRecipients(msg.get()); 

然而我得到的編譯器錯誤:

error C2783: 'void RecipientList::fillMessageWithRecipients(boost::is_base_of::type *)' : could not deduce template argument for 'T'

我有一種感覺,這與事實的類型實際上是p insed是一個指針類型,而不是它自己的類型。任何想法如何我可以正確得到類型扣除在這裏工作?

在此先感謝。

+0

強制性評論:'auto_ptr'已經廢棄了幾個很好的理由。您可能想看看[Boost.SmartPointers](http://www.boost.org/doc/libs/1_52_0/libs/smart_ptr/smart_ptr.htm) – pmr

+0

C++ 11也提供了smartpointres。 [見維基](http://en.wikipedia.org/wiki/Smart_pointer#C.2B.2B_smart_pointers)。這裏不需要提升。 – ManuelSchneid3r

+0

@pmr從你的鏈接:「這些模板是爲了補充std :: auto_ptr模板而設計的。」,在移植到C++ 11之外沒有替代auto_ptr(我不能這樣做,我更喜歡在那裏使用'unique_ptr')。 –

回答

2

我有這種感覺,你是在濫用boost::is_base_of。嵌套的type將是true_typefalse_type。這兩者都沒有意義作爲一個論點,你的指針將不能轉換爲那些。

你真正想要的是什麼:

#include <boost/type_traits/is_base_of.hpp> 
#include <boost/utility/enable_if.hpp> 

class MsgContent {}; 

class RecipientList 
{ 
public: 
    template<class T> 
    typename boost::enable_if< 
     typename boost::is_base_of<MsgContent, T>::type 
     , void>::type 
    fillMessageWithRecipients(T* t) { } 
}; 

class SomeMsg : public MsgContent {}; 

int main() 
{ 
    RecipientList recipients; 
    SomeMsg m; 
    recipients.fillMessageWithRecipients(&m); 

    return 0; 
} 
+0

但是,謝謝,'SomeMsg m'必須是一個指針類型,而不是參考:( –

+0

@RobertDailey在我的例子中它是一個指針,看看'&'。 – pmr

+0

謝謝,我忽略了這一點,我會試試這個, –

2

你應該enable_if toghether使用is_base_of。

is_base_of本身就是謂詞。

live demo

#include <boost/type_traits.hpp> 
#include <boost/utility.hpp> 
#include <iostream> 
#include <ostream> 

using namespace std; 

struct Base1 {}; 
struct Derived1 : Base1 {}; 

struct Base2 {}; 
struct Derived2 : Base2 {}; 

template<typename T> 
typename boost::enable_if< boost::is_base_of<Base1, T>, void >::type f(T* p) 
{ 
    cout << "Base1" << endl; 
} 

template<typename T> 
typename boost::enable_if< boost::is_base_of<Base2, T>, void >::type f(T* p) 
{ 
    cout << "Base2" << endl; 
} 

int main() 
{ 
    Derived1 d1; 
    Derived2 d2; 
    f(&d1); 
    f(&d2); 
} 

輸出是:

Base1 
Base2