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() );

ただし、コンパイラ エラーが発生します。

エラー C2783: 'void RecipientList::fillMessageWithRecipients(boost::is_base_of::type *)': 'T' のテンプレート引数を推測できませんでした

これは、実際に渡される型がポインター型であり、型自体ではないという事実と関係があると感じています。ここで型推論を適切に機能させる方法はありますか?

前もって感謝します。

4

2 に答える 2

2

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
于 2012-11-09T19:43:01.823 に答える
2

悪用しているように感じますboost::is_base_of。ネストされた は または のtypeいずれtrue_typeかになりますfalse_type。これら2つのどちらも引数として取る意味がなく、ポインターはそれらに変換できません。

本当に欲しいもの:

#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;
}
于 2012-11-09T19:33:34.110 に答える