以下模板将决定 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报告说他们现在有一个自 VS2008 以来的 is_abstract
类作为 TR1 的一部分(在 header type_traits
内)。但是,我的安装中似乎缺少它。
附言。由于冗长乏味的原因,我无法通过 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++ - isAbstract 模板和 Visual Studio ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/809562/