以下模板将决定T是否为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) }; 
};

例如:     struct myClass2 {virtual void f(){}};     struct myClass1 {virtual void f()= 0; };

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

然而,它在visual studio 9.0中失败并出现错误:

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

有没有人知道问题是什么以及如何解决这个问题?

MSDN 报告他们现在有is_abstract课程因为VS2008是TR1的一部分(在标题type_traits内)。但是,我的装置似乎缺少它。

PS。由于长而无聊的原因,我无法通过Boost重新实现这一点。

更新

另外,尝试更换,

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

每个,

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

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

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

没有运气 - 所有人都说不能为U推断出模板参数。

有帮助吗?

解决方案

这在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) }; 
};

注意我只需要从isAbstract<T>::的调用中删除test

其他提示

不确定,因为我已经注意到C ++已经有一段时间了,但是你可以使用

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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top