C++11中,判断一个类是否有成员函数size
,您可以定义以下测试助手:
template <typename T>
struct has_size_fn
{
typedef char (& yes)[1];
typedef char (& no)[2];
template <typename C> static yes check(decltype(&C::size));
template <typename> static no check(...);
static bool const value = sizeof(check<T>(0)) == sizeof(yes);
};
在 C++98 中是否有类似的技巧,可以在不依赖编译器扩展的情况下执行此操作,例如typeof
?
事实上,你的检测可能是错误的。
问题是你所检测到的只是C
有一个会员size
:
- 它可能是一个属性
- 它可以是具有任何签名的方法
- 甚至可能有多种方法(具有不同的签名)
如果您希望加强检测,您应该尝试仅检测right size
(无论什么权利)。这是这样一个强化的检测 http://ideone.com/JKo8p5.
template <typename T>
class has_size {
private:
typedef char Yes;
typedef Yes No[2];
template <typename U, U> struct really_has;
template <typename C> static Yes& Test(really_has <size_t (C::*)() const,
&C::size>*);
// EDIT: and you can detect one of several overloads... by overloading :)
template <typename C> static Yes& Test(really_has <size_t (C::*)(),
&C::size>*);
template <typename> static No& Test(...);
public:
static bool const value = sizeof(Test<T>(0)) == sizeof(Yes);
};
Edit: 有过载 http://ideone.com/RGeZTX.
处理不正确的技巧size
成员是really_has
结构。但我并不假装它是完美的......
在 C++11 中,事情变得更简单 http://ideone.com/AmaBrN(尽管同样冗长)因为你可以通过以下方式检测事物use直接地。因此,等效的特征是:
template <typename T>
class has_size {
private:
typedef char Yes;
typedef Yes No[2];
template<typename C> static auto Test(void*)
-> decltype(size_t{std::declval<C const>().size()}, Yes{});
template<typename> static No& Test(...);
public:
static bool const value = sizeof(Test<T>(0)) == sizeof(Yes);
};
然而,C++ 中推荐的方法是不使用特征如果可以的话;例如在函数中你可以使用decltype
就在类型签名中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)