【发布时间】:2012-03-20 19:35:41
【问题描述】:
在https://stackoverflow.com/a/1967183/134841 中,提供了一种解决方案,用于静态检查成员是否存在,可能在某个类型的子类中:
template <typename Type>
class has_resize_method
{
class yes { char m;};
class no { yes m[2];};
struct BaseMixin
{
void resize(int){}
};
struct Base : public Type, public BaseMixin {};
template <typename T, T t> class Helper{};
template <typename U>
static no deduce(U*, Helper<void (BaseMixin::*)(), &U::foo>* = 0);
static yes deduce(...);
public:
static const bool result = sizeof(yes) == sizeof(deduce((Base*)(0)));
};
但是,它不适用于 C++11 final 类,因为它继承自被测类,而 final 阻止了这一点。
OTOH,这个:
template <typename C>
struct has_reserve_method {
private:
struct No {};
struct Yes { No no[2]; };
template <typename T, typename I, void(T::*)(I) > struct sfinae {};
template <typename T> static No check( ... );
template <typename T> static Yes check( sfinae<T,int, &T::reserve> * );
template <typename T> static Yes check( sfinae<T,size_t,&T::reserve> * );
public:
static const bool value = sizeof( check<C>(0) ) == sizeof( Yes ) ;
};
在基类中找不到reserve(int/size_t) 方法。
是否有这个元函数的实现既可以在T 的基类中找到reserved(),并且如果T 是final 仍然可以工作?
【问题讨论】:
-
在 C++11 上,你可以只使用“sfinae for expressions”而不是在 C++03 中使用这种迂回的方式。
-
@JohannesSchaub-litb 寻求解决方案!我很想看看它对这种示例的影响。
标签: c++ c++11 final template-meta-programming typetraits