[英]Template type deduction failing
我正在使用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() );
但是我得到了編譯器錯誤:
錯誤C2783:'無效的RecipientList :: fillMessageWithRecipients(boost :: is_base_of :: type *)':無法推斷出'T'的模板參數
我感覺這與以下事實有關:實際傳遞的類型是指針類型,而不是類型本身。 知道如何在這里正確進行類型推演嗎?
提前致謝。
我覺得您在濫用boost::is_base_of
。 嵌套type
將為true_type
或false_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;
}
您應將is_base_of與enable_if一起使用。
is_base_of本身只是謂詞。
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.