模板类型扣除失败

时间:2012-11-09 19:31:03

标签: c++ templates boost template-meta-programming

我正在使用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(升压:: is_base_of ::类型   *)':无法推断'T'的模板参数

我有一种感觉,这与实际传入的类型是指针类型,而不是类型本身有关。知道如何在这里正确地进行类型演绎吗?

提前致谢。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:2)

您应该将is_base_of与enable_if一起使用。

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
相关问题