可能重复:
C++模板可以检查函数是否存在?
我试图确定一个类型有某个成员.这是我试过的:
template <typename T,typename U=void>
class HasX
{
public:
static const bool Result=false;
};
template <typename T>
class HasX<T,typename enable_if_c<(sizeof(&T::X)>0)>::type>
{
public:
static const bool Result=true;
};
struct A
{
int X();
};
struct B
{
int Y();
};
int main()
{
cout<<HasX<A>::Result<<endl; // 1
cout<<HasX<B>::Result<<endl; // 0
}
Run Code Online (Sandbox Code Playgroud)
它实际上是在GCC上编译和工作,但VC error C2070: 'overloaded-function': illegal sizeof operand在实例化时提供.
代码是否有问题,是否有其他方法可以做到这一点?
的确有:
typedef char (&no_tag)[1];
typedef char (&yes_tag)[2];
template < typename T, void (T::*)() > struct ptmf_helper {};
template< typename T > no_tag has_member_foo_helper(...);
template< typename T >
yes_tag has_member_foo_helper(ptmf_helper<T, &T::foo>* p);
template< typename T >
struct has_member_foo
{
BOOST_STATIC_CONSTANT(bool
, value = sizeof(has_member_foo_helper<T>(0)) == sizeof(yes_tag)
);
};
struct my {};
struct her { void foo(); };
int main()
{
BOOST_STATIC_ASSERT(!has_member_foo<my>::value);
BOOST_STATIC_ASSERT(has_member_foo<her>::value);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
从这里复制粘贴.
编辑:更新符合AFAIK的代码.另请注意,您必须知道要检查的方法的返回类型的参数.
| 归档时间: |
|
| 查看次数: |
389 次 |
| 最近记录: |