Domanda

Il modello seguente deciderà se T è astratto con g ++.

/**
   isAbstract<T>::result is 1 if T is abstract, 0 if otherwise.
 */
template<typename T>
class isAbstract
{
   class No { };
   class Yes { No no[3]; }; 

   template<class U> static No test( U (*)[1] ); // not defined
   template<class U> static Yes test( ... ); // not defined 

public:
   enum { result = sizeof( isAbstract<T>::template test<T>( 0 ) ) == sizeof(Yes) }; 
};

Ad esempio:     struct myClass2 {virtual void f () {}};     struct myClass1 {virtual void f () = 0; };

bool twoAbstract = isAbstract<myClass2>::result;
bool oneAbstract = isAbstract<myClass1>::result;

Tuttavia, non riesce in Visual Studio 9.0 con l'errore:

error C2784: 'AiLive::isAbstract<T>::No AiLive::isAbstract<T>::test(U (*)[1])' : could not deduce template argument for 'U (*)[1]' from 'myClass2'

Qualcuno ha idea di quale sia il problema e come risolverlo?

MSDN segnala che ora hanno una classe is_abstract da VS2008 come parte di TR1 (all'interno dell'intestazione type_traits). Tuttavia, sembra mancare dalla mia installazione.

PS. Per motivi lunghi e noiosi, non posso reimplementarlo tramite Boost.

Aggiorna

Inoltre, ho provato a sostituire,

template<class U> static No test( U (*)[1] ); 

con ciascuno di,

template<class U> static No test( U (*x)[1] );
template<class U> static No test( U (*)() );
template<class U> static No test( U (*x)() );

e

template <typename U>
struct U2 : public U
{
   U2( U* ) {}
};

// Match if I can make a U2
template <typename U> static No test( U2<U> x  );

e

// Match if I can make a U2
template <typename U> static No test( U2<T> x  );

Nessuna fortuna: tutti affermano che l'argomento modello non può essere dedotto per U.

È stato utile?

Soluzione

Questo funziona per me in VC9:

template<typename T>
class isAbstract
{
    class No { };
    class Yes { No no[3]; }; 

    template<class U> static No test( U (*)[1] ); // not defined
    template<class U> static Yes test( ... ); // not defined 

public:
    enum { result = sizeof( test<T>( 0 ) ) == sizeof(Yes) }; 
};

Nota che ho dovuto rimuovere isAbstract<T>:: dalla chiamata a test.

Altri suggerimenti

Non sono sicuro di aver notato C ++ per un po ', ma puoi usare

template< typename  T, typename  U>
class isAbstract
{
   class No { };
   class Yes { No no[3]; }; 

   template<class U> static No test( U (*)[1] ); // not defined
   template<class U> static Yes test( ... ); // not defined 

public:
   enum { result = sizeof( isAbstract<T>::template test<T>( 0 ) ) == sizeof(Yes) }; 
};


bool twoAbstract = isAbstract<myClass2, SomeTypeU>::result;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top