本文介绍了如何判断类在编译时是否包含某个成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说有2个类别:
struct A{ int GetInt(){ return 10; } };
struct B{ int m; };
我想在以下函数中使用类型A或B的对象
I want to use object of type A or B in following function
tempate< typename T >
int GetInt( const T & t )
{
//if it's A, I'll call: return t.GetInt();
//if its' B, I'll call: return t.m;
}
现在,由于有很多类,一些包含GetInt一些不,我不想为每个类型写专门化,我只想通过包含GetInt()或不在编译时来区分它们,我应该怎么做? / p>
Now, because there are whole bunch of classes, some contain GetInt(), some don't, I don't want to write specialization for each type, I only want to distinguish them by 'containing GetInt() or not in compile time', how should I do this ?
推荐答案
从,并假设你修复你的代码,因此 GetInt
is const,我们得到:
Stealing from here, and assuming you fix your code so GetInt
is const, we get:
HAS_MEM_FUNC(GetInt, has_GetInt);
template <bool B>
struct bool_type
{
static const bool value = B;
};
typedef bool_type<true> true_type;
typedef bool_type<false> false_type;
namespace detail
{
template <typename T>
int get_int(const T& pX, true_type)
{
return pX.GetInt();
}
template <typename T>
int get_int(const T& pX, false_type)
{
return pX.m;
}
}
template <typename T>
int get_int(const T& pX)
{
return detail::get_int(pX,
has_GetInt<T, int (T::*)() const>::value);
}
这是相当可怕的设计。您应该解决问题,而不是应用补丁。
This is pretty awful design though. You should fix the problem rather than apply a patch.
这篇关于如何判断类在编译时是否包含某个成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!